I’m working on a brick-based game in Godot and trying to move all bricks downward after an action. Here’s my code for creating the bricks:
var bricks = [
preload("res://square.tscn")
]
var balls = preload("res://ball.tscn")
var brick_location = Vector2(100, 200)
var brick_location2 = Vector2(138, 265)
func create_field():
brick_location = Vector2(100, 200 * placement_loop)
for i in range(1):
for x in range(8):
var select_brick = randi() % bricks.size()
var new_brick = bricks[select_brick].instantiate()
new_brick.position = brick_location
add_child(new_brick)
brick_location.x += 75
brick_location.x = 75
brick_location.y += 80
func create_field2():
brick_location2 = Vector2(138, 265 * placement_loop)
for i in range(1):
for x in range(7):
var select_brick = randi() % bricks.size()
var new_brick = bricks[select_brick].instantiate()
new_brick.position = brick_location2
add_child(new_brick)
brick_location2.x += 75
brick_location2.x = 75
I tried moving them using:
$square.position += Vector2(0, 50)
However, this only moves the first created brick and not all of them.
How can I move all bricks down together? Should I store them in an array and iterate through them? If so, how would I reference all instantiated bricks after they are created?
Another thought is that if all the bricks that are meant to be moving together were made the child of a single node2d, you could just move that node2d and the engine will handle moving all its children for you. This is simpler for you and makes sense in the scene tree since the bricks are naturally grouped together. It might be more efficient than doing it yourself since it’s handled within the engine instead of interpreted GDScript, but I don’t know if that matters.
You can’t do it at the same time on the whole array, you need to iterate through the array, e.g. with a for loop, and set the position for each item individually.
in your sample "brick_instances" is a string aka purely text, using for on it makes a new variable called new_brick that represents each character/letter in the string sequentially. Meaning “b”, then “r”, then “i”, then “c”, then “k” etc. you can test this out with a print
for new_brick in "brick_instances":
print(new_brick)
Then you try to access $new_brick, but because it starts with a dollar sign Godot isn’t using the new_brick variable, Godot is trying to find a child node named “new_brick”, which likely doesn’t exist.
If brick_instances exists as an Array, then you need to remove the quotes and the dollar sign.