Why does my player slide a little to a direction once it finishes moving diagonally?

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

Right now I’m making a 2D game with top-down movement.

I’ve noticed an issue with how the player moves faster diagonally when two keys are pressed, so I spent a bit more time than necessary to fix it. In the end this was the code (for movement):

vel = Vector2()

if Input.is_action_pressed("focus"):
	current_speed = SPEED / 2.0
else:
	current_speed = SPEED

if Input.is_action_pressed("left"):
	vel.x -= 1
elif Input.is_action_pressed("right"):
	vel.x += 1
	
if Input.is_action_pressed("up"):
	vel.y -= 1
elif Input.is_action_pressed("down"):
	vel.y += 1

vel = vel.normalized() * current_speed * delta

translate(vel)

It DID fix the issue, although the player will sort of slide when the two keys are released.

Using print(vel) will output the following as an example:


(8.249579, 8.249579)
(8.249579, 8.249579)
(8.249579, 8.249579)
(8.249579, 8.249579)
(8.249579, 8.249579)
(8.249579, 8.249579)
(8.249579, 8.249579)
(8.249579, 8.249579)
(8.249579, 8.249579)
(8.249579, 8.249579)
(8.249579, 8.249579)
(11.666667, 0) <-- The player sort of slides to the right here
(11.666667, 0)

My idea is that there is a bit of time between when the first key is released and when the second one is. So between that time the engine thinks that the player is still pressing one key, resulting in the “sliding.” This makes calculating when to stop or set the velocity to zero very difficult.

Is there a way to fix this? Thanks for the help (^^

:bust_in_silhouette: Reply From: GGmd

What’s in your translate function? And are you doing this inside of process or physics process?
You’re resetting the velocity at the start so it should be 0,0 as soon as you release the key from the code shown here.

I’m doing it in _physics_process.
Also the translate function is built-in in Godot.
But this answer seems simple enough to implement, thanks (^^

owlisGODOT | 2021-07-04 06:36