newbie112
newbie112

Reputation: 45

Spawning at wrong places godot

func spawnCircle(): #Spawn circle at random position every 3 seconds
    var circle = TextureButton.new()
    var texture = load("res://Assets/Circle.png")
    circle.set_normal_texture(texture)
    circleSpawnTimer.start(2.5)  #spawn next circle
    randomize()
    add_child(circle)
    circle.rect_position.x = randi() % int(rect_size.x)
    circle.rect_position.y = randi() % int(rect_size.y)
    circle.connect("pressed", self, "on_Circle_pressed", [circle]) #connect circle pressed signal and pass in its reference
    var circleDisappearTimer = Timer.new()  #Timer for circles to disappear if left unclicked
    circle.add_child(circleDisappearTimer)
    circleDisappearTimer.connect("timeout", circle, "queue_free") #delete circle on timeout
    circleDisappearTimer.start(4) #After 5seconds left unclicked , the circle will disappear

I have a circle clicker game, everything seems to be working correctly except that the circles sometimes spawn at the edge of the screen, making it only half-visible or only a a quarter of it visible. How do I make it so the circle only spawn at places that allows it to be fully visible?

Upvotes: 1

Views: 229

Answers (1)

Theraot
Theraot

Reputation: 40220

Considering that rect_position corresponds to the rectangle top-left corner. And the size of the Control (TextureButton in this case) is rect_size

It wil be out of bounds if the rect_position of the Control is closer to the bottom than its vertical size (rect_size.y), or it is closer to the right than its horizontal size (rect_size.x).

Thus, we need a range that goes from 0 to the size of the screen minus the size of the control.

Following the way you are using the random number generator, that would be:

circle.rect_position.x = randi() % int(rect_size.x - circle.rect_size.x)
circle.rect_position.y = randi() % int(rect_size.y - circle.rect_size.y)

Upvotes: 1

Related Questions