RigidBody 2D deaceleration.

Hi people,
I’m new to this forum so I hope I don’t create this post in the wrong place.
So I’ve been a gamedev since 2010 when I started with XNA, so I’m very familiar with gamedev theory, also I work as a developer (C# mostly), so the only thing that I new at is Unity.

Right now (just for practice purposes), I’m creating a Megaman engine, and since this is my third day and I tried everything (only in my free time which is 2 hours per day), I would like to ask for help.

I’m trying to have a player that have the exact behavior as Megaman (NES Series), but I’m facing with the issue that the player can’t stop moving inmediatly when I release the button (let’s say, RightArrow). I need the player to stop and don’t deacelerate, as it is doing right now. I believe this is normal because what I’m using is the following:

        if (Input.GetKey(KeyCode.RightArrow))
        {
            GetComponent<Rigidbody2D>().velocity = new Vector2(moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
        }

And I’m setting moveSpeed to 5. So when I release RightArrow, it deacelerates, giving the player some kind of friction. I had no issue with XNA since I was dealing with X and Y positions, so no speed. Then in other platforms such as Construct, I just entered a high number in Friction property, and it worked as expected.

What’s the way to handle this?

Thanks a lot!

If you want the player to stop completely, you could do it like this:

  if(Input.GetKeyUp(KeyCode.RightArrow))
  {
    GetComponent<Rigidbody2D>().velocity = new Vector2(0, GetComponent<Rigidbody2D>().velocity.y);
  }

That should stop it.

BTW: Cache the GetComponent part, use it at Start() and save it for later. It’s quite slow to do again and again (and the code doesn’t look good :slight_smile: )

1 Like

Awesome, it works, thanks for both tips!

Hey Carlos, I’ve just asked a similar question over in the scripting channel… My problem was it’s advised to use:

 if(Input.GetAxis("Horizontal") > 0)

Rather than

 GetKey("right")

This allows config and different input types… BUT the default is really floaty and causes you to accelerate slow and slide to a halt.

If you end up down the same route as I went with GetAxis go to:
Edit > Project Settings > Input…
Then open up Axes > Horizontal
And set Gravity and Sensitivity to 1000 (or more, I’m still chasing up a recommended number, I copied 1000 from what the jump button was doing by default)

Hey James,
I will try it tomorrow, thanks a lot. I’m not familarized with Axis but I will read some theory then apply it.

Again, thanks!