Area2D (Player) doesn't stop moving when user doesn't hold the key anymore

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

So a minigame I’m putting into my game is similar to this tutorial here. The difference is that with my game “enemies” only spawn at the top and go downwards, and the player can only move left and right. Plus, I’ve modified the velocity so that it doesn’t go to zero immediately after the player stops holding the key, instead slowly decreasing until it reaches zero. Here is my code:

extends Area2D

var velocity = 0
var SPEED = 10
var screen_size

func _ready():
    screen_size = get_viewport().size.x

func start(pos):
    position = pos

func _process(delta):
    if Input.is_action_pressed("ui_right"):
	    velocity += 0.1
    elif Input.is_action_pressed("ui_left"):
	    velocity -= 0.1
	if  velocity > 0.0:
		velocity -= 0.1
	if velocity < 0.0:
		velocity += 0.1
    velocity = clamp(velocity, -1, 1)

    position.x += SPEED * velocity
    position.x = clamp(position.x, -screen_size/2, screen_size/2)

func _on_Player_body_entered(body):
    $PlayerCollisionShape2D.set_deferred("disabled", true)

Slowing down after going left is no problem. When the user doesn’t hold the right arrow key until velocity hits 1, it slows down after the release just fine. However, if the velocity hits 1 and the player releases the right arrow key, the player slows until the velocity hits 0.1 and doesn’t go down anymore. I tried adding a this:

if !Input.is_action_pressed("ui_right") and \
!Input.is_action_pressed("ui_left") and \
velocity == 0.1:
    velocity = 0

Or something along those lines. I don’t have it anymore. Anyway, it didn’t help it. I’ve got no idea what’s going on. Please send help.

:bust_in_silhouette: Reply From: Thomas Karcher

Calculating with datatype float often leads to unexpected rounding errors. In your case, a remaining velocity of 0.09998 will result in 0.1 being subtracted and being added again immediately afterwards.

Adding the following line before or after “velocity = clamp(velocity, -1, 1)” should fix the problem:

if abs(velocity) < 0.1: velocity = 0

Thanks a lot!

Addie | 2019-06-07 15:54