The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates. | Twitter

0 votes
in Engine by (24 points)

Which edge? Top, bottom, left, right, some combination, or any?

Any, I think I just had an idea too. Might be bonkers though ;)

first generate randon number 1-4.

1 = top edge
2 = right edge
3 = bott... etc

if top edge then y=0, x= random (0, xmax)
if bottom edge then y = ymax, x= random (0, xmax)

and vice versa for left and right?

Yep, something along those lines should work fine. You could potentially combine top/bottom and left/right for the random part to clean it up a bit, but you've got the idea...

2 Answers

0 votes

If it's only the edges store an array of Vector2s and pick a random index. The array would have to be updated constantly if the window is resizeable.

var screen_edges : Array = []

func _ready():

    //Spawn at random point using screen_edges[rand_range(0,screen_edges.size())]
by (3,229 points)
edited by

You don't have to call randomize() each time you generate a random number. It just sets the seed used for the random number generation, so it's enough to call it once in _ready(). Also there is randi_range(), so instead of writing

s = int(round(rand_range(0.51, 4.49)))

you can simply use

s = randi_range(1, 4)

That doesn't work for me, it gives an error, even though I can see it in the documentation. Says "The method "randi_range" isn't declared in the current class???

There are a number of ways of picking a random number within a specified range. Many of them are discussed in this thread:

Regarding the above randi_range(min, max), that's documented here:

As documented, it's a method of RandomNumberGenerator object. To use it, you need an instance of that object. So, something like this:

var rng =
var ranInt = rng.randi_range(1, 4)

Sorry, my bad. As jgodfrey correctly pointed out, this method is only available on an instance of RandomNumberGenerator. Outside of this it won't work. However, you could still use this:

var random_int = randi() % 4 + 1

The %-sign represents the modulo-operator.

Alternatively you could also use ẁrapi:

var random_int = wrapi(randi(), 1, 4)
+1 vote

This is covered in the "Your first game"-section of the documentation.

by (10,634 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.