Search Unity

Player getting knocked back too fast

Discussion in '2D' started by Pixitales, May 26, 2019.

  1. Pixitales

    Pixitales

    Joined:
    Oct 24, 2018
    Posts:
    177
    This is a 2D top down game. I want to player to get knocked back far away, when collide with an enemy. The problem is, the player gets knocked back too fast that you can barely see the animation of being knocked back. How do I get smooth knockback like the player slowly slide back?

    This is on my Player script:

    Code (CSharp):
    1.     public void OnCollisionEnter2D(Collision2D other)
    2.     {
    3.         if (other.gameObject.tag == "Enemy" && health.MyCurrentValue > 0)
    4.         {
    5.             Direction = (transform.position - other.transform.position);
    6.  
    7.             MyRigidbody.AddForce(Direction.normalized * 5000, ForceMode2D.Force);
    8.         }
    9.     }
     
    Last edited: May 26, 2019
  2. A_Person_Named_Dart

    A_Person_Named_Dart

    Joined:
    Apr 14, 2018
    Posts:
    330
    add force mulitple times perhaps
     
  3. A_Person_Named_Dart

    A_Person_Named_Dart

    Joined:
    Apr 14, 2018
    Posts:
    330
    or use velocity
     
  4. N_Murray

    N_Murray

    Joined:
    Apr 1, 2015
    Posts:
    98
    Multiply your direction by time.deltaTime to get a more gradual movement
     
  5. Pixitales

    Pixitales

    Joined:
    Oct 24, 2018
    Posts:
    177
    thanks, I solved it
    I used rigidbody.MovePosition(position) and freeze direction = vector2.zero(player cant move while knockback). Then I added knockback length and distance to my original code. I removed Addforce because its too strong. New method makes the player slide back really smoothly and you can adjust the values.

    https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html
     
unityunity