43 lines
2.1 KiB
GDScript
43 lines
2.1 KiB
GDScript
class_name CompanionBehaviors
|
|
extends RefCounted
|
|
|
|
const CompanionStateType = preload("res://scripts/domain/entities/companion_state.gd")
|
|
const PathfindingType = preload("res://scripts/domain/ai/pathfinding.gd")
|
|
|
|
static func decide(companion: CompanionState, player: ActorState, enemies: Dictionary[StringName, ActorState], map: GridMapState, blocked_cells: Dictionary[Vector2i, bool] = {}) -> Dictionary:
|
|
if companion == null or not companion.is_alive():
|
|
return {"kind": &"idle"}
|
|
match companion.stance:
|
|
CompanionStateType.Stance.FOLLOW:
|
|
return _follow(companion.actor, player, map, blocked_cells)
|
|
CompanionStateType.Stance.DEFEND:
|
|
return _defend(companion.actor, player, enemies, map, blocked_cells)
|
|
CompanionStateType.Stance.SUPPORT:
|
|
return {"kind": &"idle"}
|
|
_:
|
|
return {"kind": &"idle"}
|
|
|
|
static func _follow(actor: ActorState, player: ActorState, map: GridMapState, blocked_cells: Dictionary[Vector2i, bool]) -> Dictionary:
|
|
if actor.cell.distance_to(player.cell) <= 1.5:
|
|
return {"kind": &"idle"}
|
|
var occupied := blocked_cells.duplicate()
|
|
occupied.erase(actor.cell)
|
|
occupied[player.cell] = true
|
|
var goals: Array[Vector2i] = []
|
|
for direction: Vector2i in PathfindingType.CARDINAL_DIRECTIONS:
|
|
var cell := player.cell + direction
|
|
if map.is_walkable(cell) and not occupied.has(cell):
|
|
goals.append(cell)
|
|
var path := PathfindingType.find_path_to_any(map, actor.cell, goals, occupied)
|
|
return {"kind": &"move", "to_cell": path.front()} if not path.is_empty() else {"kind": &"idle"}
|
|
|
|
static func _defend(actor: ActorState, player: ActorState, enemies: Dictionary[StringName, ActorState], map: GridMapState, blocked_cells: Dictionary[Vector2i, bool]) -> Dictionary:
|
|
var targets: Array[ActorState] = []
|
|
for enemy: ActorState in enemies.values():
|
|
if enemy.is_alive() and enemy.cell.distance_to(player.cell) <= 1.5:
|
|
targets.append(enemy)
|
|
targets.sort_custom(func(first: ActorState, second: ActorState) -> bool: return String(first.id) < String(second.id))
|
|
if not targets.is_empty() and actor.cell.distance_to(targets[0].cell) <= 1.5:
|
|
return {"kind": &"melee", "target_id": targets[0].id}
|
|
return _follow(actor, player, map, blocked_cells)
|