How to randomize the gui position that is not outside of a gui frame

  1. What do you want to achieve? Keep it simple and clear!
    Im currently trying to make a game and i need a gui where its position is random that is in the gui frame
  2. What is the issue? Include screenshots / videos if possible!
    It will sometimes get out of the gui
    Here is my script (The gui frame’s size is {0.828, 0},{0.757, 0})
local X = math.random(1,85)/100
local Y = math.random(1,73)/100
script.GuiName.Position = UDim2.new(X,0,Y,0)
  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I tried looking it on the dev forums but i can’t find it

Set your anchor point to (0.5,0.5)
Your bounds would be:

{ X : X >= Size.X/2, X <= Parent.Size.X - (Size.X/2) }
{ Y : Y >= Size.Y/2, Y <= Parent.Size.Y - (Size.Y/2) }

Example

If you have:

  • Parent frame of size 500px x 500px
  • Child frame of size 100px x 100px

A random position inside the parent frame would be:

child.Position = UDim2.new(0,math.random(50,450),0,math.random(50,450))

Thanks for the answer but i don’t really like using offsets since they aren’t really compatible on mobile

Also is it Parent.Size.X-(Size.X/2)?

You can use offsets for guis if you get AbsoluteSize or AbsolutePosition of your guis, so you’d only have to use offsets for your calculation.

Yes I will rewrite it sorry abt that

Is there any way to do this without using them?

Not really because if they’re relative sizes, the scale X size (0.5) of parent will not mean the same thing as what child sees as scale X (0.5).

Like I said you can continue to do your guis with scalars, but the calculation part can be done with offsets, then converted to scale if you so choose to:

Example of conversions

local absoluteParentSize = parent.AbsoluteSize
-- do your work for x and y
-- ...
-- ...
-- now let's say you have your x and y as offsets for the child
-- let's convert to relative
local offsetX = ...
local offsetY = ...
local relativePosition = UDim2.new(offsetX/parent.AbsoluteSize.X,0,offsetY/parent.AbsoluteSize.Y,0)