Taking damage from an enemy on collision

Hey guys,

What I have done so far is created a first person shooter where you shoot enemies that walk around and follow you. I’ve got everything working fine. I can shoot the enemies three times each, and they die etc… etc…

What I am stuck on, is getting the player to take damage when enemies collide or come into contact with the player. I tried the following script:

var health = 4;

    function OnCollisionEnter(hit: Collision){
    	if(hit.gameObject.tag == "enemy"){
    		health = health - 1;
    	}
    }
    
    function Update(){
    	if(health == 0){
    		Destroy(gameObject);
    	}
    }

This is the script to go onto the player and as you can notice, I ran into a problem, because when the enemies collide with the player, it is constantly taking down the health, and because the Update function is constantly checking how ever many times it does per frame, it basically kills the player straight away…

What I was thinking was, I need say a cool down buffer, where it takes a couple of seconds until the player can take damage again, even if an enemy is colliding with it!!!

Thanks in advance!

-Grady

This is a very basic solution, but maybe is what you want. The only change is the introduction of a WaitForSeconds() that stops the health decreasing for 2 secs. I can’t test it right now, so it’s just a suggestion. Let me know…

var health = 4;
var damage = 1;
var wait_time = 2;
var lock = 0;


    function OnCollisionEnter(hit: Collision){
        if(hit.gameObject.tag == "enemy" && lock == 0){
           DecreasingHealth();
        }
    }

    function DecreasingHealth(){
        lock=1;
        health=health-damage;
        yield WaitForSeconds(wait_time);
        lock=0;
    }

    function Update(){
       if(health == 0){
          Destroy(gameObject);
       }
    }

I would try the following approach:

  1. Create a flag (Boolean) to toggle recognition of the collision, “hasCollided”.
  2. Inside OnCollisionEnter, first check that hasCollided is false. If it is, flag it as true and calculate the damage. This should prevent subsequent calculations of the same collision.
  3. Finally, use OnCollisionExit to reset hasCollided to false. This should ensure that the objects have to separate before a subsequent collision is recognised.

I hope that solves your problem. (I’m going to be facing the same thing shortly…)