Why does my Godot object only spawn once?

  • Thread starter Darkmisc
  • Start date
In summary, the conversation was about spawning an object at the top of the screen and having it move towards the bottom before disappearing and respawning again. The code provided was not working as expected, with the object only spawning once and not repeating the cycle. The expert suggested that the mistake might be in the "queue_free()" line, which could be destroying the object at y=200 and preventing the if statement from being activated. The object is a green square and the code is attached to it to control its movement.
  • #1
Darkmisc
207
28
TL;DR Summary
I'm just starting to learn GDScript. I'd like an object to spawn near the top of the viewport, move towards the bottom, disappear and then spawn again. I can only get it to spawn once.
Hi everyone

I'd like to spawn an object at the top of the screen, have the object move towards the bottom, disappear and then spawn again at the top of the screen (to repeat the cycle). I've used the below code.

When I run it, the object spawns once, moves towards the bottom, disappears and that's it. It doesn't spawn again.

Does anyone know what I've done wrong?Thanks

gameplay:
extends Node2D
var plsquare = preload("res://MainScenes/square/square.tscn")func _ready():
    var square = plsquare.instance()
    get_tree().current_scene.add_child(square)
    square.position = Vector2(-200, rand_range(0, 100))

    if square.position.y>199:
        square = plsquare.instance()
        get_tree().current_scene.add_child(square)
        square.position = Vector2(-200, rand_range(0, 100))
square:
extends Area2Dexport var speed: float = 100
var vel:=Vector2(0,0)

func _process(delta):
    pass
    func _physics_process(delta):
    vel.y=speed
    
    position +=vel * delta
    if position.y>200:
        queue_free()
 
Technology news on Phys.org
  • #2
I use Unity, not Godot, so I don't know if I can help you. But I'll give it a shot. First, what is actually moving here? I see the position+= vel* delta line, but what is actually moving? I don't see any object that the code acts on. Is it like unity where certain things are implicit to the object the script is attached to? Also, should queue_free() be called? That sounds like it might be destroying an object.
 
  • Like
Likes Darkmisc
  • #3
The object is just a green square. Eventually, it might become an enemy in a space shooter or Tetris block.

I'm familiar with Unity, but it sounds like it might work like Godot. The script is attached to the object and tells it what to do.

I think you might have found the mistake in my code. I've destroyed the object at y=200, so the if statement might not get activated.
 

Similar threads

  • Programming and Computer Science
Replies
4
Views
1K
  • Programming and Computer Science
Replies
5
Views
1K
  • Programming and Computer Science
Replies
1
Views
922
Back
Top