Godot Version
v4.3.stable.official [77dcf97d8]
Question
Hello, I am following this tutorial in how to make a grid based movement in 2D
https://kidscancode.org/godot_recipes/4.x/2d/grid_movement/index.html
The problem comes when I modify the code so that I don’t have to press the button every time I want to move, so I put the input in the _physics_process so that when I press and hold the button, the player will continue to move in the desired direction.
This seems to cause a problem with the tween I’m using to move the player, it doesn’t have smooth movement and every time it moves forward it stops for a moment.
From what I have read, this is because I am running one tween after another instead of a continuous movement and the tween is set to stop for a moment before running the next tween.
I have tried to solve this by using Lerp instead of a tween but I don’t think I know how to use the corrutine correctly in this case because when I release the button the character stops without respecting the grid and even I can move the player diagonally.
Can anyone help me to make the movement smooth with the tween or how to use the lerp correctly? the code I use for lerp is commented
Video using Tween
Video using Lerp
Player code and tree
extends Node2D
@onready var ray : RayCast2D = $RayCast2D
var animation_speed : int = 3
var moving : bool = false
var tile_size : int = 32
var inputs : Dictionary = {
"Move_Right": Vector2.RIGHT,
"Move_Left": Vector2.LEFT,
"Move_Up": Vector2.UP,
"Move_Down": Vector2.DOWN}
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
position = position.snapped(Vector2i.ONE * tile_size)
position += Vector2.ONE * tile_size/2
func _physics_process(delta: float) -> void:
for dir : String in inputs.keys():
if Input.is_action_pressed(dir) and !moving:
move(dir, delta)
func move(dir : String, delta : float) -> void:
ray.target_position = inputs[dir] * tile_size
ray.force_raycast_update()
if !ray.is_colliding():
#var target_position : Vector2 = position + (inputs[dir] * tile_size)
#position = position.lerp(target_position, animation_speed * delta)
#var confirmation : bool = position.is_equal_approx(target_position)
#moving = true
#await confirmation
#print(position + (inputs[dir] * tile_size))
#moving = false
var tween : Tween = create_tween()
tween.tween_property(self, "position", position + inputs[dir] * tile_size, 1.0/animation_speed).set_ease(Tween.EASE_OUT)
moving = true
await tween.finished
moving = false