Search Unity

Can you give me some advise with my simple 2D controls?

Discussion in 'Getting Started' started by JapaneseBreakfast, Dec 4, 2018.

  1. JapaneseBreakfast

    JapaneseBreakfast

    Joined:
    Sep 7, 2018
    Posts:
    44
    I have a character that either slashes left or right.
    He remains in one place and enemies run at him from either left or right.
    I've also made sure the enemy's colliders are large enough, but sometimes missing a collision.

    Currently I'm using the Left or Right Arrows to fire my hit function:

    Code (CSharp):
    1. // Called only once per tap!
    2. private void Hit (Transform hitPoint) {
    3.  
    4.     Collider2D[] enemies = Physics2D.OverlapCircleAll(hitPoint.position, hitRadius, enemyLayer);
    5.  
    6.     for (int i = 0; i < enemies.Length; i += 1) {
    7.         Minion enemy = enemies[i].GetComponent<Minion>();
    8.  
    9.         if (!enemy.dead) {
    10.             Instantiate(bloodFX, hitPoint);
    11.             enemy.Die();
    12.         }
    13.     }
    14. }
    As you can see, I create OverlapCircleAll that returns an array of collisions (if any). Perfect. The problem is that sometimes a hit is not registered, what I think is happening:

    The slash animation last longer the collision circle. In other words, visually the slash is still animating and the circle collider has already disappeared. I'm not mistaken, the way I'm creating the collider, it only last a frame, while my slash animation will last a couple of frames.

    What are my best options?

    - Is there a way I can make the OverlapCircleAll last longer?
    - Should I just create a GameObject with a CircleCollider attached to it and enable and disable it within a certain time I manage in Update()?
    - Should I just use a Coroutine?

    I want to keep the gameplay fast where I can just jam on the left and right arrows without missing a collision. But that's clearly not working :(
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Those are all decent options (except maybe the Coroutine — that is the way of pain).

    Depending on how you're doing your animation, you may also be able to simply enable and disable a collider (as well as move it around) as part of the animation itself. This is a very handy trick, as it lets you visually sync the hit checking with the animation.
     
    JapaneseBreakfast likes this.
  3. JapaneseBreakfast

    JapaneseBreakfast

    Joined:
    Sep 7, 2018
    Posts:
    44
    Thanks Joe, I appreciate the answer. I went with the second solution and that's working nicely. Now I know why most 2D retro style games just use one frame for a sword slash.
     
    JoeStrout likes this.