Using both RB Velocity and AddForce?
Hello, I am working on a 2D platformer and i use Rigidbody2D.velocity to move. It is easier to stop the player if i am not pressing a key and removes acceleration. But i wanted to push the player back when there is a collision with an enemy and because the velocity is set to 0 when no key is pressed, i can't use "AddForce", the player stops in air. So i was wondering if there is a solution to keep make the player stop instantly but keep the AddForce.
Here is my code :
 void Movement()
 {
     //Move
     float horizontal = Input.GetAxis("Horizontal");
     rb2D.velocity = new Vector2(horizontal * speed, rb2D.velocity.y);
     
     //Jump
     rb2D.AddForce(new Vector2(0, jumpForce), ForceMode.Impulse);
     
     //Getting pushed back by enemy (debug)
     if(Input.GetKeyDown(KeyCode.T))
         rb2D.AddForce(new Vector2(-pushForce, 0)ForceMode.Impulse);
 }
 
              Good day.
IF velocity = 0 is applied, the addforce will have no effect.
So you need to dont apply the velocity command during the time you want it to move back.
Answer by ma9ici4n · Jun 14, 2019 at 05:20 AM
This is probably a bit late, but to fix this you can make the player be unable to move for like one third of a second when getting knocked back.
      void Movement()
      {
          //Move
          float horizontal = Input.GetAxis("Horizontal");
          if (beingknocked == true)
              rb2D.velocity = new Vector2(horizontal * speed, rb2D.velocity.y);
          
          //Jump
          if (beingknocked == false)
              rb2D.AddForce(new Vector2(0, jumpForce), ForceMode.Impulse);
          
          //Getting pushed back by enemy (debug)
          if(Input.GetKeyDown(KeyCode.T))
              rb2D.AddForce(new Vector2(-pushForce, 0)ForceMode.Impulse);
              beingknocked = true
              yield return new WaitForSeconds(0.3);
              beingknocked = false
      }
 
               This way the player gets stunned when knocked back so the rb.velocity command won't interfere with the addforce.
Your answer