Search Unity

circlecast vs collider component, creating 2d top-down melee

Discussion in '2D' started by unity_72NNT-e0FQsyKw, Apr 11, 2021.

  1. unity_72NNT-e0FQsyKw

    unity_72NNT-e0FQsyKw

    Joined:
    Feb 22, 2021
    Posts:
    13
    I'm building a topdown 2d shooter where the character has a sword melee option. I've made the sword follow mouse input and created an animation so that the sword attacks in the direction of the mouse. When the sword swings, I have two options for detecting collisions.

    option 1: use the standard circlecastall and then build a list of enemies on the layer to deal damage

    option 2: attach a capsule collider component to my sword and use ontriggerenter to execute the damage

    Which one do I choose and why?

    context: What I noticed was that by applying the collider component to an object and animating it, I can get really accurate visual representation of "Did it hit, or not". The problem is that the collider is always active so if my sword is outside my character sprite, I can still attack enemies without clicking mouse, since my sword collides. (maybe make the collider inactive and add the isActive line to the attack method?)

    What I'm trying to achieve is simply a direction and accurate sword attack. I then found the circlecastall and thought maybe this automatically turns on/off during the input event, collecting a list of collisions. That's great, but most tutorials show it just drawn at an attackPoint beside the character. (Maybe I can attach it to a child of the sword so it moves with the animation?)
     
  2. japhib

    japhib

    Joined:
    May 26, 2017
    Posts:
    65
    As you mention, the main difference is that CircleCastAll is only at a single point in time, whereas adding a collider component & doing OnTriggerEnter2D or whatever will have it be continuously active. So it just depends on whether you want to have the whole sword swing produce collisions, or only at a single moment in time.

    With the collider, you can set Collider.enabled = false when you're not attacking and then I think it won't trigger the OnTriggerEnter events.

    Alternately you can do several CircleCastAll's, like one every .2 seconds or something if you want to have multiple collisions over the course of the sword swing.
     
    unity_72NNT-e0FQsyKw likes this.
  3. unity_72NNT-e0FQsyKw

    unity_72NNT-e0FQsyKw

    Joined:
    Feb 22, 2021
    Posts:
    13
    Just wanted to add to this. You're right.

    Also, I learned that you can use the animator to turn on and off components, like a capsule collider. So for the sword swing, on triggering the animation, collider turns on and follows the sword. Once it's done, it turns off. This way you can have a moving/dynamic collider instead of a hitbox.