extends CharacterBody2D @export var unitData: Dictionary[String, Variant] = { "MoveRange": 5, "MoveRangeVi": Vector2i(5, 5), "MoveRangeV": Vector2(5, 5), "Speed": 400.0 } var grid: AStarGrid2D var currentCell: Vector2i var currentPoint: int var moveGrid: AStarGrid2D var selected: bool: set(v): selected = v; $PathPrev.visible = selected; if selected: setMoveGrid(); # if selected: MapGlobal.SetRegion(calculateMovementRegion()) var moving: bool: set(v): moving = v; $PathPrev.visible = not moving; set_physics_process(moving) signal MoveFinished var targetCell: Vector2i var movePts: Array func _ready(): selected = false moving = false func setup(_grid: AStarGrid2D): selected = true grid = _grid currentCell = pos_to_cell(global_position) targetCell = currentCell setMoveGrid() func reset(pos: Vector2): stopMove() global_position = pos currentCell = pos_to_cell(global_position) targetCell = currentCell movePts = [] $PathPrev.points = movePts currentPoint = 0 func pos_to_cell(pos: Vector2): return pos / Vector2(MapGlobal.getData()["cellSize"]) func _input(event: InputEvent) -> void: if moving: return if event.is_action_pressed("SetMarker") and selected: startMove() func setTarget(target: Vector2i): if !selected: return if moving: return if currentCell.distance_to(target) > unitData["MoveRange"]: return if target != targetCell: print("Setting target: ") movePts = MapGlobal.GetGrid().get_point_path(currentCell, target) movePts = (movePts as Array).map(func (point): return point + grid.cell_size/2.0) $PathPrev.points = movePts targetCell = target print (targetCell) func startMove(): if movePts.is_empty(): return currentPoint = 0; moving = true func stopMove(): if !moving: return moving = false 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; MoveFinished.emit(); #MapGlobal.SetRegion(calculateMovementRegion(), -unitData["MoveRangeVi"]) else: var direction = (movePts[currentPoint+1] - movePts[currentPoint]).normalized() velocity = direction * unitData["Speed"] move_and_slide() if (movePts[currentPoint+1] - global_position).length() < 4: currentCell = pos_to_cell(global_position) currentPoint += 1 func selectUnit(cell: Vector2i): if cell == currentCell: selected = true else: selected = false func setMoveGrid(): if not grid: return moveGrid = grid # [moveRange]-tiles in each direction + center var gridSize = unitData["MoveRange"] * 2 + 1 # moveGrid.set_size(Vector2i(gridSize, gridSize)) moveGrid.region = (Rect2i(global_position, Vector2i(gridSize, gridSize))) moveGrid.offset = unitData["MoveRangeV"] func GetMoveGrid() -> AStarGrid2D: return moveGrid