I’m confused about a behavior in Unity. When landing after a jump, my player slows down. I uploaded a video to show what I mean, pay attention to the speed variable in the bottom left:
I would like my character to keep their horizontal speed when landing.
My code is pretty simple, here’s the relevant part for horizontal movement, I think the variables are self-explanatory:
if (playerSpeed < maxWalkingSpeed)
{
playerBody.AddForce(Vector2.right * horizontalInput * walkingForce);
}
For jumping, it’s a simple impulseForce on the rigid body.
In the video, I’m holding right the whole time, so they should be maintaining a near constant speed. I imagine the problem is from some setting with the friction of the rigid bodies; I don’t think the problem is my code.
Any help would be appreciated. If you need more context, let me know.
I’m making a 2D platformer as well and ran into the same problem. Here’s how I fixed it:
Inside my PlayerCollision script I created a Vector2 named lastVelocity
. Inside FixedUpdate()
I constantly set this equal to the player’s current Rigidbody velocity.
Next I set up OnCollisionEnter2D()
so that it checks whether the player has collided with an object tagged “Ground” or “Platform.” If so, a custom method named PreserveMomentumOnImpact()
is called (more on this method below).
Inside PreserveMomentumOnImpact()
, I check whether lastVelocity.y
is less than -5. In other words, I check whether or not the player hit the ground/platform while falling at a fairly high rate of speed. If that was the case, then the player’s (Rigidbody) velocity is set to his last X velocity, and his current Y velocity. What this ultimately means is that if he hits the ground hard enough to normally slow him down (like in your example), his previous X velocity will replace his new one, thus negating the slowdown.
Here’s the entire PreserveMomentumOnImpact method described above:
void PreserveMomentumOnImpact()
{
if (lastVelocity.y < -5)
rb.velocity = new Vector2(lastVelocity.x, rb.velocity.y);
}
That pretty much covers everything. Be sure to let me know if this helps, and best of luck.
Create a new Physics Material 2D with 0 friction and assign that to your ground/floors.