Is there a way to use a different var then velocity with move_and_slide() in GD4

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

Hi, I’m a fairly inexperienced developer but I feel pretty comfortable with Godot. I upgraded to Godot 4 recently and one feature, the move_and_slide() function, has been bothering me.
I’m trying to make the player get knocked back whenever an enemy comes in contact. The way I would do it in Godot 3 is like this:

knockback = knockback.move_toward(Vector2(), 140 * delta)
knockback = move_and_slide(knockback)

However, in Godot 4, move_and_slide() only works with the built in variable ‘velocity’. How can I knock the player back without interfering with my movement, which uses velocity?

:bust_in_silhouette: Reply From: zhyrin

You can consider the knockback an impulse (oneshot, not continuous) velocity change.
I would calculate it as a velocity, add it to the actual velocity variable only when the knockback happens.

:bust_in_silhouette: Reply From: stormreaver

I maintain separate Vectors for each movement component I want to manipulate and track (horizontal, vertical, and lateral) , and then integrate them into the built-in velocity vector for the move_and_[slide | collide] call.