0 votes

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)
asked Jul 20 in Engine by copo de requeijinho (15 points)

1 Answer

+1 vote
Best answer

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.maptoworld` 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.

answered Jul 21 by Sakaki (60 points)
selected Jul 21 by copo de requeijinho

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.