How would I make a gui appear on a random spot on the screen

I decided I will give a shot at making a lifting simulator for fun. One thing I couldn’t wrap my head around though is making it so when you lift the weight, the gui arm would appear somewhere random on the screen, or preferably have it choose one of let’s say 5 set positions.

The issue is I don’t know the best way to approach this, and I don’t know how I would even achieve this.

I’ve tried using math.random and generating a random number, but that didn’t work of course.

Here is the portion of the script I have so far: (Local script by the way.)

local tool = script.Parent
local plr = game.Players.LocalPlayer
local gui = plr.PlayerGui.Main.LiftingImage
tool.Activated:Connect(function()
	gui.Position =    --This is the area I do not understand.
end)

Anything helps! Thanks! :smile:

9 Likes

You could make different variables that display the coordinates for the positions. Or/and then, you could use math.Random.

2 Likes

I know how to tween, Sorry if I said it wrong. I want it to appear somewhere random on the screen, not just go there.

1 Like

Don’t worry, I was mistaken. i apologize. I will re-correct it asap.

1 Like

To acheive this you can use math.random like so:

gui.Position = UDim2.new(math.random(), 0, math.random(), 0)

5 Likes

To generate a random position on the screen you could do something like this:

local r = Random.new()

local function GetRandomPosition()
    return UDim2.new(r:NextNumber(0,1),0,r:NextNumber(0,1),0)
end

This would work, and apply using a Scale position value. If you wanted to use Offset, you’d do the same thing but go from 0,0 to screenSize

21 Likes

Or something like @RetributionVI said. That is more easier than what I said.

1 Like

Let’s not compare speed here, because the speed difference is negligible. There are only slight differences in the code sample: one calls a global and the other creates an object of the Random class, assigned to a local upvalue.

The Random object and math.random use the same algorithm but depending on your use case, you may want to change up which one you’re using. As Random is an object, that also means it sports a plethora of API that you may want to use.

Here’s a scenario: instead of calling math.randomseed (which globally affects seeding and can cause conflictions if multiple scripts are relying on it), you can pass a seed to Random for deterministic results or leave it blank. No argument in Random.new (no fixed seed) pulls a seed from an internal source of entropy and will effectively be local towards that object.

4 Likes

Ok, got it. Thanks for correcting me.