Kinemticbody 2d Does not move smoothly and stop when need to (Code Problem)

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

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

:bust_in_silhouette: Reply From: deaton64

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)