From 29d68068ac6ad6dcf71d81a0f7fde6d4627b4e7a Mon Sep 17 00:00:00 2001 From: veclav talica Date: Fri, 24 Nov 2023 15:11:00 +0500 Subject: [PATCH] move logic out of controller to context, fixed position_to_cell_position() --- nodes/GridContext.gd | 9 ++++++++- nodes/GridController.gd | 14 +++++++++----- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/nodes/GridContext.gd b/nodes/GridContext.gd index 5f21175..7c036bd 100644 --- a/nodes/GridContext.gd +++ b/nodes/GridContext.gd @@ -7,7 +7,14 @@ class_name TK_GridContext export var cell_size: Vector2 = Vector2(64, 64) func position_to_cell_position(p_position: Vector2) -> Vector2: - return Arithmetic.vector2_mod(global_position - p_position, cell_size) + return p_position / cell_size func is_cell_traversible(p_cell_position: Vector2) -> bool: return true + +func try_moving(p_node: Node2D, p_cell_position: Vector2) -> bool: + if not is_cell_traversible(p_cell_position): + return false + + p_node.position = cell_size * p_cell_position + return true diff --git a/nodes/GridController.gd b/nodes/GridController.gd index eb5dd72..a8358d4 100644 --- a/nodes/GridController.gd +++ b/nodes/GridController.gd @@ -4,19 +4,23 @@ class_name TK_GridController ## Composable 4-way grid controller. ## Depends on placement below some Node2D below some GridContext. +# todo: Turn-based logic context. + signal moved(p_new_cell_position) +var _grid_context_cache: Node2D + +func _enter_tree() -> void: + _grid_context_cache = _get_grid_context() + func _input(p_event: InputEvent): var direction := InputUtils.input_event_to_4way_direction(p_event) if direction == Vector2.ZERO: return - var context := _get_grid_context() - var cell = context.position_to_cell_position(get_parent().global_position) + var cell = _grid_context_cache.position_to_cell_position(get_parent().position) var new_cell = cell + direction - if context.is_cell_traversible(new_cell): - # todo: Should we move the outmost node2d? - get_parent().position += context.cell_size * direction + if _grid_context_cache.try_moving(get_parent(), new_cell): emit_signal("moved", new_cell) func _get_grid_context() -> Node: