Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Velocity and Impulse

Discussion in 'Scripting' started by ScaryFace, Apr 20, 2020.

  1. ScaryFace

    ScaryFace

    Joined:
    Aug 7, 2015
    Posts:
    12
    Heya Guys

    I am polishing my characters movement, and i want him to get knocked back when hit. no i have managed to get a result but i need some deeper understanding of whats happening here. my code below.

    I accept input from my controller to move velocity directly.

    Code (CSharp):
    1.         if (canMove && moveHorizontal != 0)
    2.         {
    3.             rb2d.velocity = new Vector2(moveHorizontal, rb2d.velocity.y); // change in velocity
    4.             animator.SetFloat("Speed", Mathf.Abs(moveHorizontal));
    5.  
    6.             if(controllerY && animator.GetFloat("Speed") > 0)
    7.             {
    8.                 animator.SetTrigger("Sliding");
    9.             }
    10.         }
    and KnockBack is called when my character is in range and takes a hit. thrustVal is a negative or positive value parsed in depending on what side the player and enemy interact. I have tried AddForce but the below seemed to workbetter.

    Code (CSharp):
    1.     public void KnockBack(float thrustVal)
    2.     {
    3.         rb2d.velocity = new Vector2(thrustVal, transform.position.y);
    4.     }
    My Question is why wont my KnockBack Function work when I remove the "(&& moveHorizontal)" parameter in my canMove IF statement.

    and since I have implimented the above code my character has started sliding a little wtf ?

    your feedback is much appreciated.
     
  2. ScaryFace

    ScaryFace

    Joined:
    Aug 7, 2015
    Posts:
    12
    Ok so I realized the reason my player character is sliding is because i have inadvertently removed "0" from being a parameter in the canMove Velocity statement. So the player is sliding to a stop every time.

    And i am assuming, that My Velocity is actually being set to Zero every single frame because of the input retrieved. and KnockBack(); will never work because velocity.x is still being reset to zero every frame.