Vector3 and math.random issue

I’m trying to give three attachments randomised WorldPositions, confined within a small area. Here’s my code:

local hrpCF = player.Character.HumanoidRootPart.CFrame
for i = 1, 3 do
     local offset = Vector3.new(hrpCF.LookVector *  math.random(1, 8)
     + hrpCF.UpVector * math.random(0, 1) + hrpCF.RightVector * math.random(0, 1))
     * math.random(0, 1) * math.random(1, 4) - hrpCF.UpVector * 2

     attachments[i].WorldPosition = startingPoint + offset
end

Within the for loop’s scope, line one and two’s purpose is to generate a Vector3 weighted randomly in each direction. Line three is supposed to give it a random magnitude, and move it down by two.

Currently, no matter what, I get: offset = (0, -2, 0). I’m guessing this means that all my math.randoms are returning zero. Anyone know what I’m doing wrong?

math.random(int,int) returns an integer in the range (inclusive)
use math.random() for scalar

1 Like

Thanks, I didn’t realise that, I misread the documentation. However, I’ve changed all my math.random(0, 1)s to math.random(), but I’m still getting (0, -2, 0).

Vector3.new(hrpCF.LookVector  *  math.random(1, 8)
+ hrpCF.UpVector * math.random()
+ hrpCF.RightVector * math.random())
* math.random() * math.random(1, 4) - hrpCF.UpVector * 2

Found the issue, you are putting a vector value, inside a vector value… The result is Vector3.new(0,0,0) for some reason which is new haven’t heard it before, I’m surprised it doesn’t error in the console.

proof: copy and paste into the command bar

    local hrpCF = CFrame.new()
    local randomVector = hrpCF.LookVector *  math.random(1, 8) + hrpCF.UpVector * math.random(0, 1) + hrpCF.RightVector * math.random(0, 1)
    print(randomVector) --randomizes as expected
    local offset = Vector3.new(randomVector)
    print(offset) -- always 0,0,0

So the expected result is this:

local hrpCF = player.Character.HumanoidRootPart.CFrame
for i = 1, 3 do
    local randomVector = hrpCF.LookVector *  math.random(1, 8) + hrpCF.UpVector * math.random(0, 1) + hrpCF.RightVector * math.random(0, 1)
    local downVector = hrpCF.UpVector * 2
    local offset = randomVector - downVector
     attachments[i].WorldPosition = startingPoint + offset
end
2 Likes

Thanks a bunch, that seems to have solved it :slight_smile: