Reputation: 15
I have code for what happens when the enemy collides with the player using a rigid body on the player and clicking the is trigger on the collider in the inspector. When the player hits the enemy, the number of lives go down. I now have an empty game object (track) which has a rigid body and ticked the is trigger on the box collider, that one enemy moves toward. Once the enemy gets to the trigger, it is supposed to move back towards another empty game object (backTrack) to make it look like it is walking back again. At any point, if the player hits the enemy, the life count goes down by 1 and the enemy respawns at the start position. My problem is that I can't get it to distinguish between colliding with the player and track because at the minute, when the enemy hits track, it does what should be done if the player had hit the enemy and the enemy respawns at start position. Here is my code:
private bool triggered = false;
public GameObject track1;
void moveBackTrack(){
float move1 = moveSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards (transform.position, backTrack.position, move1);
}
void OnTriggerEnter(Collider col)
{
if (!triggered)
{
triggered = true;
if (col.gameObject = track1) {
moveBackTrack ();
} else {
Destroy (gameObject);
print ("Collision Enter: " + col.name);
GameManager.Instance.lives -= 1;
GameManager.Instance.setLivesText ();
GameManager.Instance.SpawnTrackEnemy ();
}
}
}
Upvotes: 0
Views: 1960
Reputation: 817
Set a tag ID for the player and enemy objects, then subscribe to the OnCollisionenter event of your track. This will fire when any collision occurs between another object and the collider of your track object.
void OnCollisionEnter(Collision col){
GameObject collidedWith = col.gameObject;
if(collidedWith.tag == "PlayerTagName"){
//do player collided logic here
}
else if(collidedWith.tag == "EnemyTagName"){
//do enemy collided logic here
}
}
By handling each object by its Tag name individually, you can better maintain your code, making it easier to code to each separate condition. I recommend setting up a similar OnCollissionEnter handler for your player and enemies as well, depending on how many conditions might occur in the logic of your game.
Upvotes: 1