86 lines
2.2 KiB
GDScript
86 lines
2.2 KiB
GDScript
extends CharacterBody2D
|
|
|
|
@export var unitData = {
|
|
"MoveRange": 5,
|
|
"MoveRangeVi": Vector2i(5, 5),
|
|
"MoveRangeV": Vector2(5, 5),
|
|
"Speed": 400.0
|
|
}
|
|
|
|
var grid: AStarGrid2D
|
|
var currentCell: Vector2i
|
|
var currentPoint: int
|
|
|
|
var selected: bool:
|
|
set(v):
|
|
selected = v; $PathPrev.visible = selected; 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
|
|
|
|
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 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 _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 calculateMovementRegion():
|
|
var region := Rect2i(pos_to_cell(global_position - unitData["MoveRangeV"]), unitData["MoveRangeVi"] * 2)
|
|
return region
|