Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to choose either one of three integers?

I am trying to make an airdrop system such that the plane spawns in from different directions of 50 studs away from the centre. Here is an image of what I am saying: Image

My code uses math.random(-50,50) which will select numbers in the range of -50 to 50 which is not what I want. Is there anyway for it to choose either -50, 0 or 50? Using math.random(1,3) for a 33% chance of choosing any 1 number is too tedious and confusing for me.

local centre = script.Parent.CenterPoint

while wait (5) do
	local chance = math.random(-50, 50)
	local chance2 = math.random(-50, 50)
	local jet = Instance.new("Part")
	jet.Parent = workspace
	jet.Name = "Jet"
	print("Okay")
	jet.CFrame = CFrame.new((centre.Position + Vector3.new(chance, 0, chance2)),workspace.CenterPoint.Position)
	print(jet.Position)
end

2 comments

0

local chance = math.random(-1, 1) * 50

0

Thank you!

1 answer

✓ Accepted answer

if in future you want to have numbers other than -50, 0, 50, say 240, 6, -25, 12 you can create a table which will contain these numbers and then pick a random number it.

local numbers = { 240, 6, -25, 12 }

print( numbers[1] ) -- 240
print( numbers[2] ) -- 5
print( numbers[3] ) -- -25
print( numbers[4] ) -- 12

as you can see, numbers[2] gets us the second number, numbers[4] gets the last fourth number, 12. the idea here is to generate random number from to 1 to 4 and type in numbers[random number from 1 to 4].

local numbers = { 240, 6, -25, 12 }

print( numbers[ math.random(1, 4) ] ) -- random number from `numbers`

however one drawback is that if you add a number into the table:

local numbers = { 240, 6, -25, 12, 8 }

then you will have to change the code from math.random(1, 4) to math.random(1, 5) since there are 5 numbers now, instead of that, use #numbers, this is the amount of numbers in the table:

local numbers = { 240, 6, -25, 12, 8 }

print( #numbers ) -- 5, meaning math.random(1, #numbers) is equal to math.random(1, 5)

local chance = numbers[ math.random(1, #numbers) ]
local chance2 = numbers[ math.random(1, #numbers) ]

1 comment

0

Thanks for teaching me this method!

This discussion is preserved as it was. New answers, comments, and votes are closed.