extends CharacterBody2D @export var SPEED = 400.0 var grid: AStarGrid2D var currentCell: Vector2i var currentPoint: int var moving: bool: set(v): moving = v; $PathPrev.visible = not moving; set_physics_process(moving) var targetCell: Vector2i var movePts: Array func _ready(): moving = false func setup(_grid: AStarGrid2D): grid = _grid currentCell = pos_to_cell(global_position) targetCell = currentCell func pos_to_cell(pos: Vector2): return pos / grid.cell_size func _input(event: InputEvent) -> void: if moving: return if event is InputEventMouseButton: if event.pressed and event.button_index == MOUSE_BUTTON_LEFT: startMove() elif event is InputEventMouseMotion: var target = Vector2i(pos_to_cell(event.position)) if target != targetCell: movePts = grid.get_point_path(currentCell, target) movePts = (movePts as Array).map(func (point): return point + grid.cell_size/2.0) $PathPrev.points = movePts targetCell = target func startMove(): if movePts.is_empty(): return currentPoint = 0; moving = true func _physics_process(delta: float) -> void: if currentPoint == movePts.size() - 1: velocity = Vector2.ZERO global_position = movePts[-1] currentCell = pos_to_cell(global_position) $PathPrev.points = []; moving = false else: var direction = (movePts[currentPoint+1] - movePts[currentPoint]).normalized() velocity = direction * SPEED move_and_slide() if (movePts[currentPoint+1] - global_position).length() < 4: currentCell = pos_to_cell(global_position) currentPoint += 1