0
\$\begingroup\$

I've created a basic attack combo system that chains 3 attacks together.

When the player clicks the mouse button, it enables a boxCollider2D attached to the player.

The boxCollider is a trigger and will cause damage to a valid target using OnTriggerEnter2D.

This doesn't seem to be very responsive, and often will not work if the target is stationary. I've thought about trying Raycasts as an alternative but am looking for advice on how to handle this properly.

public class Attack : MonoBehaviour
{
     private int comboIndex;
     public float lastAttack;
     private Animator _animator;
     private string[] attackName;
     private float comboResetTimer;
     private BoxCollider2D _hitbox;


     private void Awake()
     {
         attackName = new[] {"Attack1", "Attack2", "Attack3"};
         _animator = GetComponent<Animator>();
         _hitbox = GetComponent<BoxCollider2D>();
     }

     private void Update()
     {
         var canAttack = Input.GetMouseButtonDown(0);

         if (canAttack && comboIndex < attackName.Length)
         {
             _animator.SetTrigger(attackName[comboIndex]);   

             _hitbox.enabled = true;
             comboIndex++;
             comboResetTimer = 0f;
         }

         if (comboIndex > 0)
         {
             comboResetTimer += Time.deltaTime;
             if (comboResetTimer > lastAttack)
             {
                 _animator.SetTrigger("Reset");
                 comboIndex = 0;
                 _hitbox.enabled = false;
             }
         }
     }
 }
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

"will not work if the target is stationary"

Exactly. The physics engine checks for collision when something moves. If you don't have movement, it doesn't think it needs to check.

In particular, Rigidbodies can go to sleep if they're not moving, meaning the physics engine will skip processing them until another moving object hits them, or a script applies force/velocity/other physics effect to them. This can save a lot of processing in complex scenes.

You can force your player's Rigidbody2D to wake up by calling body.WakeUp() at the same time that you enable the hitbox. That ensures physics checks will run on that object this frame, even if all the objects nearby are stationary.

Or, to manually check for overlaps in a box on specific frames, use the OverlapBox method.

\$\endgroup\$

You must log in to answer this question.

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