hadean-godot/Scripts/Positional.gd

87 lines
1.7 KiB
GDScript
Raw Normal View History

2024-05-13 18:16:23 -04:00
@tool
extends Node2D
class_name Positional
enum State {
CLEAN,
UPDATE_POSITION
# UPDATE_TILE_POS
}
@export var quantize_in_editor = true:
set(val):
quantize_in_editor = val
_quantize()
@export var size: Vector2i = Vector2i.ONE:
set(val):
size = val
_quantize()
# - - - - - - - - - - - - - - - -
@onready var grid = Util.find(Grid)
var _worldbox: Rect2 = Rect2(0, 0, 0, 0)
var _tilebox: Rect2i = Rect2i(0, 0, 0, 0)
var state: State = State.CLEAN
var has_adjusted_positions_this_frame = false
func _ready():
set_notify_transform(true)
_quantize()
func _process(_delta):
has_adjusted_positions_this_frame = false
if state == State.UPDATE_POSITION:
_quantize()
func _enter_tree():
set_notify_transform(true)
if grid != null:
grid.register_tile(self)
func _exit_tree():
if grid != null:
grid.remove_tile(self)
func _notification(what: int) -> void:
if what == NOTIFICATION_TRANSFORM_CHANGED:
_quantize()
func _tile_pos_updated():
pass
func _size_updated():
pass
func _position_updated():
pass
func _quantize():
if grid == null || !Engine.is_editor_hint() || !quantize_in_editor:
return
if has_adjusted_positions_this_frame:
state = State.UPDATE_POSITION
return
var top_left_world_pos = position - grid.tile2world_size(size - Vector2i.ONE) / 2
var tile_pos = grid.world2tile(top_left_world_pos)
_worldbox = grid.tile2world_rect(Rect2i(tile_pos, size))
position = _worldbox.get_center()
state = State.CLEAN
has_adjusted_positions_this_frame = true
func _derive():
pass
func _update_boxes():
pass
# func set_tile_pos(pos: Vector2i):
# pass
func get_worldbox():
return Rect2(_worldbox)
func get_tilebox():
return Rect2i(_tilebox)