Reputation: 13
so... I am trying to make a grid movement like those in the pokemon games and I have followed the guide on kidscancode.org. The code works, but when I hold down the key to move, I want to continue moving in the corresponding direction until I let go (of course in a grid pattern) the code that I have is this:
extends Area2D
onready var ray = $RayCast2D
onready var tween = $Tween
export var speed = 30
var tile_size = 16
var inputs = {"move_right": Vector2.RIGHT, "move_left": Vector2.LEFT, "move_up": Vector2.UP, "move_down": Vector2.DOWN}
func _ready():
position = position.snapped(Vector2.ONE * tile_size)
position += Vector2.ONE * tile_size/2
func _unhandled_input(event):
if tween.is_active():
return
for dir in inputs.keys():
if event.is_action_pressed(dir):
move(dir)
func move(dir):
ray.cast_to = inputs[dir] * tile_size
ray.force_raycast_update()
if !ray.is_colliding():
move_tween(dir)
func move_tween(dir):
tween.interpolate_property(self, "position", position, position + inputs[dir] * tile_size, 1.0/speed, Tween.TRANS_SINE, Tween.EASE_IN_OUT)
tween.start()
with this code, I am able to move in any direction in a grid pattern but I have to press the keys n times to move n times. I want to be able to hold down the arrow key and move until I let go of it. Can anyone pls help me?
Upvotes: 1
Views: 673
Reputation: 1729
Move your _unhandled_input Code into the _physics_process function like this:
func _physics_process(delta):
if tween.is_active():
return
for dir in inputs.keys():
if Input.is_action_pressed(dir):
move(dir)
This way your code is checked in an interval and not only if an input was pressed. Node that you have to replace the "event" property to static "Input".
if you already have code that is handled in your _physics_process you might want to change the if statement, because otherwise nothing is processed if the tween is active.
func _physics_process(delta):
if not tween.is_active():
for dir in inputs.keys():
if Input.is_action_pressed(dir):
move(dir)
#code entered here will now be executed, even if the tween is not active
Upvotes: 2