Kinematic Body started sliding off ramps after implementing acceleration

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By o k

I used this tutorial to learn how to implement FPS movement and then used this tutorial to implement acceleration and friction. Before I added acceleration the player was able to stand on ramps just fine, but now after implementing acceleration the player starts sliding of the ramp when he stops how do I fix this?

physics process function:

velocity.y += gravity * delta
var desired_velocity = get_input() 

if desired_velocity.x != 0:
	velocity.x = lerp(velocity.x, desired_velocity.x * max_speed, acceleration)
else:
	velocity.x = lerp(velocity.x, 0, friction)

if desired_velocity.z != 0:
	velocity.z = lerp(velocity.z, desired_velocity.z * max_speed, acceleration)
else:
	velocity.z = lerp(velocity.z, 0, friction)

velocity = move_and_slide(velocity, Vector3.UP, true)
if jump and is_on_floor():
	velocity.y = jump_speed

While I don’t know if this is related to your problem or not, I’d be really leery of those != 0 checks. Those could be failing for you at times due to floating point errors. One way to improve that would be to change those code blocks to be something like:

if !is_equal_approx(desired_velocity.x, 0)

See details here:

@GDScript — Godot Engine (stable) documentation in English

jgodfrey | 2020-11-17 19:24

1 Like
:bust_in_silhouette: Reply From: AndyCampbell

I would recommend checking two things:

  1. Your first component (velocity.y += gravity * delta) will always set a downward velocity, even when the character is rested on the floor. When your character is on the floor it will immediately collide and if this happens on a slope the call to move_and_slide may try to slide down the slope. So, it could be a good idea to either only apply gravity when your character is not on the ground, or to explicitly set the y component of velocity to 0 when your character is on the ground (except when jumping). You can determine when your character is on the ground with is_on_floor method. Docs here

  2. Alternatively, check out move_and_slide_with_snap - docs here. This tries to make your character stay on a surface. That might solve your problem, but you need to remember to not use that when the character is jumping or falling.

So, I’ve considered this as a solution and I’ve tried it and it sort of works. The one issue that I came across is that players will now not slide down slopes that they may want to slide down because they are considered on the ground but no gravity is being applied to them.

If anyone comes up with a more standard way of doing this, please share. It seems like friction, gravity, and stopping on slopes still hasn’t been figured out by the community.

blurrred | 2022-07-03 21:18