- Home /
Collision between two moving clones
Hi,
I'm trying to achieve a collision detection between two (or more) instances of a prefab.
For example we have two enemies walking to the same position on the tile grid. (The game field is a Tile Grid setup with XZ axes where as Tiles have 1x1 size)
On each enemy prefab we have the following setting (see img) http://i60.tinypic.com/az876c.jpg
Here are a pic of the game http://i60.tinypic.com/qrdd07.jpg
It's really easy to check if two enemies collide. But the problem here is that OnCollisionEnter fires twice (for enemy1 and enemy2)
void OnCollisionEnter(Collision target)
{
if(target.gameObject.tag == "enemy")
{
// enemy collision occured
// do something
}
}
Now if I want to code special behaviour for each enemy i really don't know how to do it.
Heres what I want to achieve
enemy1 - should walk to the final position and wait one second
enemy2 - should rotate to the movement direction of enemy1 and move forwad (get bounced away from enemy1)
Sure I could do
void OnCollisionEnter(Collision target)
{
if(target.gameObject.name == "enemy2")
{
var enemy2 = target.gameObject.GetComponent<Enemy>();
// first stop movement of enemy2 immediatly
enemy2.StopMovement();
// rotate the enemy2 to the enemy1 direction
enemy.transform.rotation = transform.rotation;
// move enemy2 to the next tile
enemy.MoveStraight(enemy.transform.position + enemy.transform.forward);
// now do enemy1 logic (finish movement and wait 1 second on the new position)
// then continue random movement
}
}
But the condition name== "enemy2" is too static... What if we have 3-x enemies?
To summarize:
Question 1: How it can be avoided to call OnCollisionEnter for every enemy if they collide each other? Whats the better way to do it?
Question 2: What if we have more than two enemies, how we could handle this case? Should I Store the enemies in a List and loop through this list in OnCollisionEnter Method? I dont know...
I minimized the source to the relevant parts so that its better readable.
Thank you, best regards Regenrek
Your answer
Follow this Question
Related Questions
How to refer to a collision between clones of the same prefab? C# 1 Answer
How to setup collision with freshly generated mesh and prefabs 1 Answer
Is there a better way to check for a collision with a prefab than by name or tag? 2 Answers
Change Parent of Multiple Instantiated Objects 1 Answer
Code works fine until I turn the object it interacts with into a prefab. 1 Answer