How can I reset an object's (the player's, specifically) horizontal velocity to 0?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Joshinja
:warning: Old Version Published before Godot 3 was released.

I’m trying to use the Godot 2D physics (a RigidBody2D to be more specific) to create a retro arcade platformer, but the one problem I can’t seem to solve or find a solution for anywhere is to reset the player’s horizontal velocity back to 0.
Please don’t judge me for my terribly sloppy code, I’m new to python-like coding. :slight_smile:
My code for moving the player left and right:

if not_moving:
	print('NOT MOVING')
	set_axis_velocity(Vector2(0,0))
	
else:
	if (go_left and not go_right):
		set_axis_velocity(Vector2(-movespeed,0))
	if (go_right and not go_left):
		set_axis_velocity(Vector2(movespeed,0))

The not_moving variable is defined early in my code as being true “if not (go_left or go_right)”
I know for a fact my not_moving variable works for detecting when neither the left or right arrow key is pressed because I set it to print to the console.

The go_left and go_right variables are working too, because pressing the respective arrow key will apply the velocity.

The only thing is, when I release both arrow keys, the player just keeps moving in the last pressed direction. I’m trying to create a platformer with very tight controls, so this doesn’t bode well at all. If anyone can help, please do!

Thanks in advance,
Josh

:bust_in_silhouette: Reply From: Joshinja

Quick Update; I found a fix to this problem, so I’ll write it here for any people with this problem in the future. Apparently (or so I conjecture), setting either of the Vector2 values at 0 for the set_axis_velocity function will make them not change. So, in order to make it not 0, I just set it to be “0.001”. This may not be the best fix but it works.

In short, just change the Vector2 value you’re trying to reset to something extremely low like 0.001 to fix the problem.

You can increase the damp or use _integrate_forces (custom integrator) for a more control of the rigid behavior too.

Check platformer demo, it uses the custom integrator to modify the rigid body state.

eons | 2016-12-26 12:13

:bust_in_silhouette: Reply From: Christian

The proper way to control simulation is by using the simulation. If you directly set variables like velocity you are working against the physics instead of controlling it.
To null a force you just have to apply an opposite one.
Inertia is the resistance in changing movement so the opposite force you have to apply to archive 0 velocity using the simulation itself is “-current_velocity * inertia”

:bust_in_silhouette: Reply From: YeOldeDM

Get! Do! Set!

# Get!
var lv = get_linear_velocity()


# Do!
if LEFT and not RIGHT:
	lv.x = -movespeed
elif RIGHT and not LEFT:
	lv.x = movespeed
else:
	lv.x = 0


# Set!
if lv != get_linear_velocity():
	set_linear_velocity(lv)