0 votes

Hi All,

I am trying to let the kinematicbody2d (player) make some simpel moves but I have got two problems:
1- The "player" does not moce smoothly
2- When the key for movement is released de "player" keeps moving.

I wrote the following code:

enter code here
extends KinematicBody2D

export var speed = 0
var velocity = Vector2()
var direction = Vector2()



func _ready() -> void:
 pass 

func _physics_process(delta: float) -> void:

var is_moving = Input.is_action_pressed("ui_down") or Input.is_action_pressed("ui_up") or Input.is_action_pressed("ui_right") or Input.is_action_pressed("ui_left") 

if is_moving:
    speed = 50

    if Input.is_action_pressed("ui_up"):
        velocity.y -= 1 
    elif Input.is_action_pressed("ui_down"):
        velocity.y += 1
    elif Input.is_action_pressed("ui_right"):
        velocity.x += 1
    elif Input.is_action_pressed("ui_left"):
        velocity.x -= 1
else:
    speed = 0

direction += velocity * delta * speed

move_and_slide(direction)

Thank you in advance

in Engine by (29 points)

1 Answer

0 votes

Hi,
Your direction value is always increasing, so the object will always keep moving. I think move_and_slide already accounts for delta, so you don't need that.
Also, you're repeating your if statements to check for movement, which I don't think you need to do.
If you want to check for 4 way movement, the elif's need to be if's.

This works for me:

extends KinematicBody2D

export var speed = 100
var velocity = Vector2()
var direction = Vector2()


func _ready() -> void:
 pass 

func _physics_process(delta: float) -> void:

    velocity = Vector2(0, 0)
    if Input.is_action_pressed("ui_up"):
        velocity.y += -1 
    if Input.is_action_pressed("ui_down"):
        velocity.y += 1
    if Input.is_action_pressed("ui_right"):
        velocity.x += 1
    if Input.is_action_pressed("ui_left"):
        velocity.x += -1

    velocity = velocity.normalized() * speed

    move_and_slide(velocity)
by (1,817 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.