Who collided first
I am trying to find a way to see which object collided first. The first object to hit the second object should destroy the object.
I tried a lot of code, but I'm out of ideas on how it can be done.
My pseudo code in C# would be:
private void OnCollisionEnter(Collision collision)
{
if (gameObject("Player")) hit first
{
Destroy("Enemy");
}
else if
{
Destroy ("Player);
}
}
I'm just not sure exactly how it would be done.
If anyone has any hints or is able to point me in the right direction. I'd appreciate it. I feel like I'm pretty close I just can't figure out a way to implement it.
In collision detection, the concept of "collision intention" (meaning objectA wanted to hit objectB and collided with it) does not really exist. The objects are colliding, period. You could check the directions the objects are facing/moving to give you an abstract representation of intention.
Where is this script attached?
The scripts are attached to the player and the enemy also has one because they have health. I was hoping there was a way to figure out who collided first, but I suppose the best way might be to put an invisible block like a finger to poke the enemy or player that way if they poked the back or front they would collide ins$$anonymous$$d.
As I have indicated, ins$$anonymous$$d of using an additional collider, you could use mathematics to compare the directions the objects are facing to give you an idea of "who attacked who".
The following code has not been tested.
private void OnCollisionEnter(Collision collision)
{
float directionDotProduct = Vector3.Dot( transform.forward, collision.transform.forward );
bool isBehindOther = Vector3.Dot( transform.forward, collision.transform.position - transform.position ) > 0;
// $$anonymous$$eans if the current object collided with the "back" of the other object
// Then, destroy the other object
if ( directionDotProduct > 0 && isBehindOther )
{
Destroy( collision.transform.gameObject );
}
// You don't need the else
// Because the current gameObject will be destroyed by the same component attached to the other object
}
https://docs.unity3d.com/$$anonymous$$anual/UnderstandingVectorArithmetic.html
Your answer
Follow this Question
Related Questions
Collision or Triggers both not working. 3D. 1 Answer
Function called when a GameObject doesn't collide with ANYTHING 1 Answer
Player falls through destroy collider 1 Answer
What is the different between OnTriggerEnter and OnCollisionEnter ? 2 Answers
Preventing A Teleporting GameObject From Passing Through Walls 2 Answers