- Home /
Collision Events - Executing Code once per Collision Across Multiple Objects
I'm trying to create a script to handle collision between two objects, which are balls.
For example, a billiards game, but instead of the cue ball coming to a complete stop when it hits another ball. I want the cue ball to reverse directions, as well as applying its impulse to the ball it hit. Here is my code:
private void OnTriggerEnter2D(Collider2D collision)
{
if (gameObject.tag == "Ball")
{
if (collision.gameObject.tag == "Ball")
// Check if the ball we are executing on is a moving ball
if (System.Math.Abs(Velocity) > 0)
{
Velocity = -Velocity;
}
// If this ball wasn't already moving
else
{
Velocity = collision.gameObject.GetComponent<Ball>().Velocity;
}
}
}
The issue I'm having is that, when a moving ball contacts a non-moving ball, depending on the order the collision event executes, it can do one of two things:
Execute order correctly, ie. Non-Moving ball starts moving in the correct direction and moving ball switches directions
Order is incorrect ie. Moving ball switches directions, but when non-moving ball sets it's new, non-zero, velocity, it sets it to the 'switched' direction on the original moving ball. So, now both balls are moving in the same direction.
What changes do I need to make sure the collision event effects both balls, independently, but correctly?
Your answer
![](https://koobas.hobune.stream/wayback/20220612142129im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
2D box colliders not touching but are colliding, how to fix? 0 Answers
Weapon System with collide detection (Helps with script pls)!!! 0 Answers
Why is my collision script not working? 1 Answer
(C#) Changing color of SpriteRenderer in script causing gameObject to not render 1 Answer
rigidbody2D.addforce in collider 1 Answer