TowerGameProto/scripts/PathfindObstacle.gd

69 lines
1.8 KiB
GDScript3
Raw Permalink Normal View History

2025-04-16 22:56:14 +01:00
extends Node2D
class_name PathfindObstacle
@export var radius: float = 32
@export var added_weight: float = 0.0
@export var solid: bool = false
@export var enabled: bool = true:
set(value):
if value != enabled:
update(value)
enabled = value
var world: World
var previous_tiles: Array[Vector2i] = []
var previous_position: Vector2 = Vector2()
func _ready() -> void:
world = find_parent("TileMap")
previous_position = global_position
update(true)
func _exit_tree() -> void:
update(false)
func _process(delta: float) -> void:
if global_position != previous_position:
previous_position = global_position
if enabled:
update(false)
update(true)
func get_overlapped_tiles() -> Array[Vector2i]:
var top_left_pos: Vector2i = world.local_to_map(world.to_local(global_position) - Vector2(radius, radius))
var bottom_right_pos: Vector2i = world.local_to_map(world.to_local(global_position) + Vector2(radius, radius))
var ret: Array[Vector2i] = []
for x in range(top_left_pos.x, bottom_right_pos.x+1):
for y in range(top_left_pos.y, bottom_right_pos.y+1):
var tile: Vector2i = Vector2i(x,y)
if world.get_cell_source_id(tile):
continue
ret.append(tile)
return ret
func update(enable: bool):
var tiles: Array[Vector2i]
if enable:
tiles = get_overlapped_tiles()
previous_tiles = tiles
else:
tiles = previous_tiles
for tile in tiles:
if solid:
world.astar_grid.set_point_solid(tile, enable)
var weight: float = world.astar_grid.get_point_weight_scale(tile)
#print("Reading tile %s weight: %f" % [tile, weight])
if enable:
weight += added_weight
else:
weight -= added_weight
#print("Updating tile %s with weight %f" % [tile, weight])
#if weight > 1:
#world.set_cell(tile, 0, Vector2(1,1))
#else:
#world.set_cell(tile, 0, Vector2(0,0))
world.astar_grid.set_point_weight_scale(tile, weight)