Hey, so I’m working on a game where Guis (in this case, TextButtons) get spawned on the player’s screen at random positions. I’m not sure how to do this. I’ve looked at some other DevForum posts and copied/pasted some of the code I saw, but the TextButtons sometimes spawned only partially on the screen. I have a Frame at the center of the screen, which I want to be the border for these Textbuttons. How do I make them randomly spawn inside this Frame, so they don’t clip through the sides of the device screen?
1 Like
Substract the Gui size from how far it can spawn
local button= --whatever button you may have
local rng= --however you get your random number
--This is assuming you have anchor point set to 0,0
local maxX=math.clamp(rng,0,1-button.Size.Scale.X)
local maxY=math.clamp(rng,0,1-button.Size.Scale.Y)
button.Position=Udim2.FromScale(maxX,maxY)
1 Like
It’s not too difficult. Use the scale values for X and Y and apply the same values for the AnchorPoint. This way, if the position is UDim2.new(1, 0, 1, 0)
, your anchor point will be Vector2.new(1, 1)
. This ensures that your frame won’t go off the player’s screen.
You can test this little example:
local Container = script.Parent
while true do
local newPosX = math.random(0, 100) * 0.01
local newPosY = math.random(0, 100) * 0.01
local newFrame = Instance.new("Frame")
newFrame.Position = UDim2.new(newPosX, 0, newPosY, 0)
newFrame.AnchorPoint = Vector2.new(newPosX, newPosY)
newFrame.Size = UDim2.new(0, 100, 0, 100)
newFrame.Parent = Container
task.wait(0.5)
end
If you have any questions, don’t hesitate to ask me!
1 Like
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.