68 lines
1.7 KiB
GDScript
68 lines
1.7 KiB
GDScript
extends CharacterBody2D
|
|
|
|
@export var SPEED = 400.0
|
|
var grid: AStarGrid2D
|
|
var currentCell: Vector2i
|
|
var currentPoint: int
|
|
var selected: bool:
|
|
set(v):
|
|
selected = v; $PathPrev.visible = selected;
|
|
var moving: bool:
|
|
set(v):
|
|
moving = v; $PathPrev.visible = not moving; set_physics_process(moving)
|
|
|
|
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
|
|
|
|
func pos_to_cell(pos: Vector2):
|
|
return pos / grid.cell_size
|
|
|
|
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 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
|
|
|
|
func selectUnit(cell: Vector2i):
|
|
if cell == currentCell:
|
|
selected = true
|
|
else:
|
|
selected = false
|