Player movement bug in grid-based controls

Godot Version



Hello, I’m trying to make a grid-based movement for my game. I managed to do it with some tutorials and my own knowledge to fix some weird things, but now I have another bug. The player can move in 4 directions (UP, DOWN, LEFT, RIGHT), and when I press only one key it is fine but when I press two keys in vertical and horizontal movement (Ex. UP & LEFT) the player goes up and returns to the same tile or moves backwards. Here’s a gif:

Grid Based Movement Bug Godot 4
And here’s the code:

extends Node2D

@export var self_node:Node2D
@export var speed: float = 0.05
var moving = false

var moving_direction: Vector2 = Vector2.ZERO

func _ready():
	$RayCast2D.target_position = Vector2.DOWN * 32

func move(dir) -> void:
	if moving:
	if moving_direction.length() == 0 && dir.length() > 0:
		var movement = Vector2.DOWN
		match dir:
				movement = Vector2.DOWN
				movement = Vector2.UP
				movement = Vector2.LEFT
				movement = Vector2.RIGHT
		$RayCast2D.target_position = movement * 32
		if !$RayCast2D.is_colliding():
			moving = true
			moving_direction = movement
			var new_pos = self_node.global_position + (moving_direction * 32)
			var tween = create_tween()
			tween.tween_property(self_node, "position", new_pos, speed).set_trans(Tween.TRANS_LINEAR)
			tween.tween_callback(func(): moving_direction = Vector2.ZERO)
			moving = false

We’re missing some information to help you out with this one. Like when is the move function being called? What are the possible values of dir?

Not sure if this is the only problem but moving = false should probably be inside the callback function.