Unwanted Collision Across Multiple Targets


I have pretty much finished the Glitch Garden section of the 2D Unity course, and this is something that I noticed that wasn’t addressed. In this specific case, a rock is meant to collide with a lizard, deal damage to it, and then destroy itself, thus only allowing it to collide with one lizard. However, if two lizards are stacked on top of each other, which will occur because they stop to attack when they reach a defender, the rock will collide with both of them on the same frame and deal damage to both, not just one. What are some potential solutions to have the rock only hit one lizard?

Hi Nebulator,

Welcome to our community! :slight_smile:

What you could do is to add a new empty child to the lizard prefab. Assign a Collider2D to it. This collider is supposed to check if there is an Attacker in front of it. If there is one, the lizard stops and waits.

If the lizards are allowed to stack, you could add a Health variable to the rock script. When its collision method gets called, you check with an if-statement whether the variable is not null. If it’s not null, you attack that health object. If it is null, you call GetComponent<Health>() on the colliding game object and assign the returned Health object to the variable and attack. This way, your rock focuses only on the Health object assigned to the variable.

Did this help? :slight_smile:


See also:

Thank you Nina, this did help! It gave me a few new ideas try and practice, but I ended up following your first suggestion with one alteration. If a second lizard (or other attacker) collides with one that is already attacking a defender, it stops there and starts attacking the same target, regardless of distance. It will continue to check the state of the attacker it’s colliding with until it’s destroyed.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms