How to use mouse clicks to move in a grid

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

Hi everyone. So I want to make a TBS with grid movement. I managed to make it work so far with keyboard inputs. However, I wish to use left mouse clicks instead of the keyboard (sorta like movement in Into the Breach). Here is my code so far

extends Area2D

onready var ray = $RayCast2D##Instancia o raycast
onready var tween = $Tween##Instancia o Tween

export var speed = 3##Velocidade de movimento
var tile_size = 16 ##Tamanho do tile
var target = Vector2()
var inputs = {"ui_right": Vector2.RIGHT,
	"ui_left": Vector2.LEFT, 
	"ui_up": Vector2.UP, 
	"ui_down": Vector2.DOWN}##Atribui os inputs

func _ready():
	position = position.snapped(Vector2.ONE * tile_size)##Snappa o player no grid
	position += Vector2.ONE * tile_size / 2 ##Centraliza o player no tile

func _unhandled_input(event):##Verifica a direcao do movimento
	if tween.is_active():
		return##Ignora inputs enquanto roda o tween
	for dir in inputs.keys():
		if event.is_action_pressed(dir):

func move(dir):##Movimenta o jogador de acordo com o tamanho do tile
	ray.cast_to = inputs[dir] * tile_size##Ve a direcao de movimento e casta o raycast
	ray.force_raycast_update()##Forca o raycast
	if !ray.is_colliding():

func move_tween(dir):##Animacao
	tween.interpolate_property(self, "position", position, 
	position + dir * tile_size, 1.0 / speed, Tween.TRANS_SINE, Tween.EASE_IN_OUT)
:bust_in_silhouette: Reply From: Sakaki

You can use a Tilemap to create a virtual grid and then an A* node to find the best path between 2 cells, finally converting it to a world position.

In the Tilemap, some useful methods you would use are Tilemap.world_to_map to map the position of the character and find its current position in the grid, then Tilemap.map_to_world` to convert the cell you get from the A* to a world position.

In the A* you’d use AStar2D.add_point for each walkable cell in your Tilemap, then you can use AStar2D.get_point_path passing the current cell ID and the target cell ID, it returns an array with all the middle points the character shall walk through to reach the target point.

Thank you so much for answering. I was trying to avoid using AStar because it feels like overkill to me, but I guess I’ll have to study it. Again, thanks a lot <3

copo de requeijinho | 2020-07-21 18:47