in Engine

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...

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 = []

screen_edges.append(Vector2.ZERO)
screen_edges.append(Vector2(get_viewport().size.x,0))
screen_edges.append(Vector2(0,get_viewport().size.y))
screen_edges.append(get_viewport().size)

//Spawn at random point using screen_edges[rand_range(0,screen_edges.size())]
``````
by (3,259 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:

https://docs.godotengine.org/en/latest/classes/class_randomnumbergenerator.html#method-descriptions

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 = RandomNumberGenerator.new()
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)