1
\$\begingroup\$

For context, I have a player that can use a bow or a spear to shoot enemies in a 2D side scroller game. The bow shoots arrows and the spear shoots itself, and they both have rigidbody2Ds attached.

When the spear or arrow hits an enemy that also has a rigidbody2D, it gets destroyed as intended, however this also causes the projectile to knock back the enemy. I'm assuming this happens because the colliders hit each other right before being destroyed since the projectile moves at a semi-high speed.

Is there any way to work around this?

\$\endgroup\$
2
  • \$\begingroup\$ For easier answering your question you should post the relevant code as well (collision and movement of weapon). Is there a special reason for the rigidbody? Rigidbody is basically saying this body has a physical mass and when two of those collide (your enemy and the weapon), they do as physics do. Reducing or increasing mass might be an easy fix but can introduce other weird behaviour. \$\endgroup\$
    – Zibelas
    May 26 at 17:16
  • \$\begingroup\$ @Zibelas thanks for the heads up, I'm new to this site, so ill be sure to do that next time! \$\endgroup\$
    – Peecee
    May 26 at 22:00

1 Answer 1

1
\$\begingroup\$

The simplest way to fix this is to make the arrow or spear's collider have isTrigger = true during flight.

A trigger collider detects collisions, but does not resolve collisions by applying impulses to shift the objects apart. You'd handle the collision event in OnTriggerEnter2D(Collider2D other) instead of OnCollisionEnter2D(Collision2D collision).

If you need spears and arrows to have collision resolution at other times, you can set isTrigger back to false during those times.

Or if you need both behaviours simultaneously, you can do this with two colliders on separate layers, and layer masks filter which collisions get processed. Something like this:

  • Each character has:

    • trigger collider on "hurtbox" layer
    • non-trigger collider on "character" layer (interacts with "terrain" layer but not "projectile" layer)
  • Each projectile has:

    • non-trigger collider on "projectile" layer (which interacts with "terrain" and "hurtbox" layers but not "character" layer)

I put the extra collider on the character on the assumption that you're likely to be spawning many projectiles and fewer characters, so this minimizes the expense of the extra collider. It also gives you flexibility to tune the physics of the character for terrain interactions separately from their combat physics - using a more permissive hurtbox for example, or a rounder navigation footprint to avoid snagging on small obstacles.

\$\endgroup\$
1
  • \$\begingroup\$ This turned out to be a much simpler solution than I thought, makes me question why I haven't thought of this earlier haha. Thanks! \$\endgroup\$
    – Peecee
    May 26 at 22:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .