Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | mmarramarco | |
Old Version | Published before Godot 3 was released. |
I am making a board game in which I have hextiles. I am instancing hextiles in a hex formation. After that, I would like to updates the neighbour of each tile, so that I can start to implement graph functions.
Here is how I check the and want to add the neighbours to each tile :
var look_up_table_neighbour = [Vector2(1,0), Vector2(1,-1), Vector2(0,-1), Vector2(-1,0), Vector2(-1,1), Vector2(0,1)]
func hex_neighbour(var hex, var direction):
var dir = look_up_table_neighbour[direction]
return Vector2(hex.tile_position.x + dir.x, hex.tile_position.y + dir.y)
func update_neighbours():
for hex in get_children():
for i in range(0,6):
var corresponding_neighbour = get_child(get_children().find(hex_neighbour(hex,i)))
hex.add_neighbour(corresponding_neighbour)
And here is my tile script :
export var tile_position = Vector2()
var neighbours = []
func add_neighbour(var hex):
if not neighbours.has(hex):
neighbours.append(hex)
hex.neighbours.append(self)
var label = get_node("Label")
label.set_text(str(neighbours.size()))
My first problem is the Array.find function. What does it exactly do? Does it compare each parameter of the object inside of it? Or does compare the ID of object?
My second problem would be in accessing the variable “neighbours” in other hex. However I think what I put here works (just the find function that blocks me).
Regarding your first question
[!] No guarantee here because I am not a dev…
I believe the objects inside an array are compared by reference (pointer) and the find-function returns the position of the first object which has the same reference in memory. This can be important when some of your objects have the same value and therefore they are referencing to the same memory block.
I tried to investigate this further with this script (save it as array_test.gd
and run it inside a terminal with godot -s array_test.gd
):
#array_test.gd
extends SceneTree
func _init():
# Declare a, b, c
var a = Vector2(0,0)
var b = Vector2(1,0)
var c = Vector2(0,0) # <- Same value as 'a' but different variable
# Append all to the array
var arr = Array()
arr.append(a)
arr.append(b)
arr.append(c)
# Find their positions
print("a: ", arr.find(a)) # <- 0
print("b: ", arr.find(b)) # <- 1
print("c: ", arr.find(c)) # <- 2
quit()
The print statements are as follows:
a: 0
b: 1
c: 0
This could substantiate my thesis but I am no c++ expert so please don’t blame me if my conclusion is wrong.
I am not sure if this behaviour is the same with more complex objects. Will investigate further when I find the time.
rolfpancake | 2017-12-12 19:07