Help please im have a problem

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By abbos

Hi, I’m making a 2D game, but I’m having problem
How can I create squares that are infinite in number and come down from the top of the game scene?
That is, I copy a square through the code

It might be a better idea to summarise your question or problem in the title.

cammil | 2020-07-12 08:37

:bust_in_silhouette: Reply From: njamster

First you need to create a new scene for the squares. You could use a Polygon2D-node for that. Or simply apply a square texture to a Sprite- or TextureRect-node.

Then you can instance that scene in your game scene:

const SQUARE_SCENE = preload("<PathToSquareScene>")

var t = 0.0

func _ready():
    var spawn_timer = Timer.new()
    spawn_timer.connect("timeout", self, "_on_SpawnTimer_timeout")
    spawn_timer.timeout = 1.0
    add_child(spawn_timer)
    spawn_timer.start()

func _on_SpawnTimer_timeout():
    var new_square = SQUARE_SCENE.instance()
    new_square.global_position = Vector2(512, 0)
    add_child(new_square)

Now in order for the squares to actually fall down you need to attach a script to your square scene that will move the square downwards each frame:

const SPEED = 5 # pixels per second

func _process(delta):
    global_position.y += SPEED * delta

You probably want to free squares once the leave the screen, use a VisibilityNotifier-node for that! Also you might want to randomize the starting position of a square along the x-axis. If you haven’t yet, I’d recommend you work through this.