Search code examples
godotgdscript

Godot 2D WASD Movement


I have a trouble with a 2D Godot Project.

I wrote the following code in the KinematicBody2D script:

extends KinematicBody2D

export var speed = 250
var motion = Vector2()

func _physics_process(delta):
    motion = Vector2.ZERO
    if Input.is_action_just_pressed("ui_left"):
        motion.x = -speed
    if Input.is_action_just_pressed("ui_right"):
        motion.x = speed
    if Input.is_action_just_pressed("ui_up"):
        motion.y = -speed
    if Input.is_action_just_pressed("ui_down"):
        motion.y = speed
    motion = move_and_slide(motion)
    pass # Replace with function body.

The problem is that my player is only moving a few pixels and stops while I'm pressing the W, A, S, D or the arrow keys.

What I've done wrong?

Thank you all!


Solution

  • The function is_action_just_pressed tells you if the named action※ was just pressed. It will not continue returning true if the action is held.

    This, combined with the fact that you are erasing motion each physic frame motion = Vector2.ZERO, result in the object moving one physics frame and then it stops.

    If you want to know if the action is currently pressed - independently of when it began being pressed - use is_action_pressed instead.

    ※: The actions you can use with these functions are configured in the Project Settings. You will find them on the "Input Map" tab.