Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Random position in a range?

Asked by
manith513 121
4 years ago

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

Log in to vote
4
Answered by
brianush1 235 Moderation Voter
4 years ago

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.

0
ahhh thank you manith513 121 — 4y
Ad
Log in to vote
-1
Answered by
Benbebop 1049 Moderation Voter
4 years ago
Edited 4 years ago

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.

1
This is wrong brianush1 235 — 4y
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. Benbebop 1049 — 4y
0
I appreciate you trying though :) manith513 121 — 4y

Answer this question