How can i make gui elements spawn at random position | at given area

Hey developers,

i need help with somthing.

I want to make gui elements take random positions, in the given area..

(The green frame is the area.) and i don't want elements spawn in other area.

I am not good at math so, please help!

2 Likes

Find the size x/y of the area, then remove the width of the circles, so if the width was 50 then if the area was 100, 100 then it’d be 50, 50.
Once you have that, simply set the position to a random spot within it, since if the circles are parented there, it should make it right.

circle.Position = UDim2.new(math.random(-50, 50), math.random(-50, 50))

I am not gonna test it but I believe it should work.

1 Like

Thanks it worked! imma mark it as solution.

1 Like

Hold up, it actually worked? I was iffy it was even gonna work.

Btw it should be UDim2 , but thanks!

1 Like

Oh yeah, oops! What is vector2 used for anyway?

You can read the post by roblox: Vector2 | Documentation - Roblox Creator Hub

1 Like

Huh, just read it and it seems interesting, well anyway good luck with your game!

1 Like

Wait for some reason now it didn’t work it worked before!

like when i joined the game and the position of my circle is -11

and i didn’t even changed anything i just reopened studio.

Maybe check your code, you might accidentally forgot to save your work.

Hmm, maybe try to do the math.random with a starting value of 0, if redoing it and saving your work doesn’t fix it.

No, everything is fine! idk whats the problem now

You are changing only the Xoffset and Xscale of the UDim2.new(); function. The way I’d do is that you put the scales (X and Y) to 0 and then math.random(); the offsets of X and Y.

Defined UDim2.new() function:
image

The code which should work:

circle.Position = UDim2.new(0, math.random(-50, 50), 0, math.random(-50, 50))

or use UDim2.fromOffset(); function

circle.Position = UDim2.fromOffset(math.random(-50, 50), math.random(-50, 50))

Ah, so I think I know what’s going on.
Did it work fine in studio?
If it worked fine in studio, then what about the actual published game?

I think your position is changing because you have an offset when playing the actual game. You want to use a scale to get it to position correctly on every screen.

Exactly what I was suggesting. But you may have to do tweaking with the scaling to get it to work with respect to how you want it.

Yeah now its working fine! i’ve test it too many times :wink: