the character moves right but not left

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

I have written the exact code an online tutorial suggested but the player character only moves right when I press the assigned key but not left. here’s the code:

extends KinematicBody2D

var motion = Vector2(0,0)
const speed = 400

func _physics_process(delta):
if Input.is_action_pressed(“left”) and not Input.is_action_pressed(“right”):
motion.x = -speed
if Input.is_action_pressed(“right”) and not Input.is_action_pressed(“left”):
motion.x = speed
else:
motion.x = 0
move_and_slide(motion)

:bust_in_silhouette: Reply From: timothybrentwood
if Input.isactionpressed("left") and not Input.isactionpressed("right"):
    motion.x = -speed
elif Input.isactionpressed("right") and not Input.isactionpressed("left"):
    motion.x = speed
else:
    motion.x = 0

Make the second if an elif.

What was happening when you pressed left motion.x was set to -speed. Then it evaluated Input.isactionpressed("right") and not Input.isactionpressed("left") which turned out to be false and so the else condition fired setting motion.x to 0.