Search Unity

2D top view game - Dash through enemy with a dynamic rigidbody

Discussion in '2D' started by Altia, Jan 29, 2021.

  1. Altia

    Altia

    Joined:
    Nov 14, 2014
    Posts:
    13
    Hello community,

    I am working on a 2D top view game (zelda like style), and I am blocking on point during the implementation: I have added a Dash feature, allowing the main character to quickly go from a point A to a point B. That being said I would like to have the main character go through enemies while dashing (meaning no collision with them). Collision with walls or objects should still happen and stop the movement.
    My main character and enemies are using Rigidbody 2D in the Dynamic mode so that engine manages the collision usually.
    Do you have any idea how to manage that?

    I have seen one solution I might test which switch the enemies into Kinematic mode just during the dash duration, but I am not confortable with this as it will also stop enemies from moving because I use the "AddForce" function to manage all movements.

    Thanks
     
  2. MarekUnity

    MarekUnity

    Unity Technologies

    Joined:
    Jan 6, 2017
    Posts:
    203
    Hello @Altia! Assuming that your player and your enemies are on different layers, you could temporarily disable the collision between player and enemies using Physics2D.IgnoreLayerCollision.
    At the beginning of your dash you could call:
    Code (CSharp):
    1. Physics2D.IgnoreLayerCollision(yourPlayerLayer, yourEnemyLayer, true);
    and after the dash ends:
    Code (CSharp):
    1. Physics2D.IgnoreLayerCollision(yourPlayerLayer, yourEnemyLayer, false);
    This way, player won't collide with any object on the "yourEnemyLayer" while dashing. Please note that two first arguments of the IngoreLayerCollision method are integers. You can convert name of your layer (eg. "Default", "Enemy" etc.) to int using LayerMask.NameToLayer.

    Hope this helps!
     
    robo36, toelit and Altia like this.
  3. Altia

    Altia

    Joined:
    Nov 14, 2014
    Posts:
    13
    Hello @MarekUnity ! Wow this solution looks definitely great, let me try this :)
    Many thanks for your quick answer and the top notch solution :)
     
    MarekUnity likes this.
  4. Altia

    Altia

    Joined:
    Nov 14, 2014
    Posts:
    13
    This solution works like a charm, many many thanks for helping me :):):)
     
  5. MarekUnity

    MarekUnity

    Unity Technologies

    Joined:
    Jan 6, 2017
    Posts:
    203
    That's great! I'm glad it works for you :)