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

Random position in a range?

So because nobody has answered my previous question yet I am writing a new one where I have come up with a new idea that should in theory work but isn't. here is the code

local part = script.Parent

local function createblock()
	local block = Instance.new("Part", game.Workspace)
	local xvalue = math.random(-56.505, -99.505)
	local yvalue = 35
	local zvalue = math.random(104.5, 159.5)
	block.Position = Vector3.new(xvalue, yvalue, zvalue)
end


while true do
	createblock()
	wait(.2)
end

I seems fine what it does is I have set a range with a math.random sequence so it will get a random position in a certain range. When I run it is has an error message on line 5 with the x value saying like interval is empty. I tried multiple times it didn't work. I then tooked the -99.505 and changed it to a positive number to see what would happen it worked fine just not in the range I wanted it to. Can I not have a negative then a negative number in a math.random function?

2 answers

✓ Accepted answer

math.random expects the first number to be the lowest. Since -99.505 < -56.505, you should use math.random(-99.505, -56.505) instead.

1 comment

0

ahhh thank you

It can not sadly only the minimum number is 1 (See here), though you can just switch to positive then multiply the output by (-1) to get the range you want.

math.random(56.505, 99.505)*(-1)

Also its best to put brackets around negative numbers, not just in scripting but general mathematics.

3 comments

1

This is wrong

0

Your right, thanks. I read "math.random returns a uniform pseudo-random integer in the range [1, m]." on the page I linked and mistook it to mean that was the complete range.

0

I appreciate you trying though :)

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