detect whether a gameobject has passed through two others,
I am developing a game which consist of three balls. How can I find out if one of them has passed through the two other balls ? The balls are on a 2D screen. I want to call a function after one of them is passed and right after all the balls are stopped.,
Answer by MrDiVolo · Apr 29, 2016 at 03:15 PM
Consider using the OnTriggerEnter (and/or OnTriggerExit) method, to detect the objects entering each other. Then a script attached to each of them, that looks something like this;
public class Ball : MonoBehaviour
{
private Ball m_lastCollision;
private bool m_colliderBoth;
public void OnTriggerEnter(Collision p_collision)
{
Ball ball = p_collision.gameObject.GetComponent<Ball>();
if (ball != null)
{
if (m_lastCollision == null)
m_lastCollision = ball;
else if (ball != m_lastCollision)
{
m_lastCollision = ball;
m_colliderBoth = true;
}
}
}
}
The above script stores a reference to the last object with a Ball script attached to it that collided with this object. As well as a boolean to determine if both objects have been collided with, determined by if the m_lastCollision is not null and not equal to the current ball being collided with.
If you still need to balls to collide with other objects, you'll need to consider Collision Layers to allow the balls to pass through each other, whilst still colliding with other objects in the scene.
Hope this helped.