tochie-kit/nodes/GridContext.gd

48 lines
1.5 KiB
GDScript

tool
extends TK_Context
class_name TK_GridContext
## todo: Cell visualization.
## todo: Integration of TileMap.
export var cell_size: Vector2 = Vector2(64, 64) setget _set_cell_size
signal cell_size_changed(p_old_cell_size, p_new_cell_size)
var _colliders: Dictionary # Node to null (set)
func local_position_to_context_position(p_position: Vector2) -> Vector2:
return p_position / cell_size
func is_path_traversible(p_game_object: Node2D, p_from: Vector2, p_to: Vector2) -> bool:
for collider in _colliders:
if not collider.is_path_traversible(p_game_object, p_from, p_to):
return false
return true
# todo: Effectful traversal.
func try_moving(p_game_object: Node2D, p_from: Vector2, p_to: Vector2) -> bool:
if not is_path_traversible(p_game_object, p_from, p_to):
return false
p_game_object.position = cell_size * p_to
return true
func register_collider(p_collider: Node) -> void:
_colliders[p_collider] = null
if p_collider.connect("child_exiting_tree", self, "_on_collider_exiting_tree") != OK:
assert(false)
func _on_collider_exiting_tree(p_collider) -> void:
if not _colliders.erase(p_collider):
pass
func _set_cell_size(p_new_cell_size: Vector2) -> void:
if p_new_cell_size.x == 0 or p_new_cell_size.y == 0:
push_error("Cell size cannot be zero")
return
var cell_size_cache = cell_size
cell_size = p_new_cell_size
emit_signal("cell_size_changed", cell_size_cache, p_new_cell_size)