player moves forever

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

he walks forever until he collides with an object how do i fix that
he used to move normally when i used is action released but it made the game lag so i changed it

extends KinematicBody2D

onready var _animated_sprite = $AnimatedSprite

export var speed = 200
export var gravity = 32
export var jump = 600
var direction = Vector2.RIGHT

var motion = Vector2.ZERO

func _physics_process(delta):

if Input.is_action_pressed("ui_right"): 
	motion.x = speed  
	direction = Vector2.RIGHT
	$AnimatedSprite.flip_h = false"walk")
elif Input.is_action_pressed("ui_left"): 
	$AnimatedSprite.flip_h= true"walk")
	motion.x = -speed 
	direction = Vector2.LEFT
if motion.x == 0 && motion.y == 0:
	motion.x = lerp(motion.x, 0, 0.25) 
	if direction==Vector2.RIGHT:
	elif direction==Vector2.LEFT:

if is_on_floor(): 
	if Input.is_action_pressed("ui_up"):
		motion.y = -jump

motion.y += gravity + delta

motion = move_and_slide(motion, Vector2.UP)
:bust_in_silhouette: Reply From: MisterMano

Note that once you set motion.x to any value, it never goes back to zero. No wonder you’re getting infinite movement.

Following your current code, it should have something like this:

if Input.is_action_pressed("ui_right"): 
#move right
elif Input.is_action_pressed("ui_left"): 
#move left
else: #<<- if neither right, nor left, is pressed
motion.x = 0

It will probably bring your character to an immediate full stop, but the idea that you should keep in mind is that you need to set movement back to 0 if no keys are pressed.