Created
December 20, 2021 13:02
-
-
Save N-Carter/c2a8712b9e8e1d1bfdfb4fac5980c5a4 to your computer and use it in GitHub Desktop.
Focus Connecting script for Godot's GridContainer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends GridContainer | |
export var connect_on_ready : bool | |
func _ready() -> void: | |
if connect_on_ready: | |
connect_children() | |
# get_child(0).grab_focus() | |
func connect_children() -> void: | |
var num_children := get_child_count() | |
if num_children == 0: | |
return | |
var complete_rows := int(float(num_children) / columns) | |
var columns_in_last_row := 0 | |
var total_rows := complete_rows | |
if complete_rows * columns < num_children: | |
total_rows += 1 | |
columns_in_last_row = num_children - columns * complete_rows | |
print("Columns: %d, complete rows: %d, columns in last row: %d, num children %d" % [columns, complete_rows, columns_in_last_row, num_children]) | |
var index := 0 | |
for y in total_rows: | |
for x in columns: | |
# print("%d, %d" % [x, y]) | |
var child := _get_grid_child(x, y) | |
var rows_in_this_column := complete_rows | |
if x < columns_in_last_row: | |
rows_in_this_column = total_rows | |
if rows_in_this_column > 0: | |
child.focus_neighbour_top = _get_sibling_path(child, _get_grid_child(x, wrapi(y - 1, 0, rows_in_this_column))) | |
child.focus_neighbour_bottom = _get_sibling_path(child, _get_grid_child(x, wrapi(y + 1, 0, rows_in_this_column))) | |
child.focus_neighbour_left = _get_sibling_path(child, get_child(wrapi(index - 1, 0, num_children))) | |
child.focus_neighbour_right = _get_sibling_path(child, get_child(wrapi(index + 1, 0, num_children))) | |
index += 1 | |
if index >= num_children: | |
return | |
func _get_grid_child(x : int, y : int) -> Control: | |
var index = x + y * columns | |
var child = get_child(index) if index >= 0 and index < get_child_count() else null | |
return child as Control | |
func _get_sibling_path(child : Node, sibling : Node) -> NodePath: | |
if sibling: | |
return child.get_path_to(sibling) | |
return NodePath() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment