Get random direction between two directions

Im trying to get a random direction between a parts LookVector and its RightVector.

My code is definitely wrong:

local direction = newCF.LookVector + newCF.RightVector
local direction2 = newCF.LookVector - newCF.RightVector
	
local randDir = Vector3.new(math.random(direction.X - 1, direction.X + 1),direction.Y, math.random(direction.Z - 1, direction.Z + 1))
local randDir2 = Vector3.new(math.random(direction2.X - 1, direction2.X + 1), direction2.Y, math.random(direction2.Z - 1, direction2.Z + 1))
1 Like

Me and a programmer friend of mine were talking about this, this is what he came up with:
(everything below the line is his words not mine)


Here are 2 ways to go about it!

The first one is guarenteed to work good, but with some tiny caveats.

The second is less likely to work, because I didn’t test it yet, but if it does work, it will work better than the first one.

-- This version is a lot simpler, but some directions may be more likely to occurr than others. In other words, you might not have uniform distribution.
local lookVec = newCF.LookVector
local rightVec = newCF.RightVector

local randomVecBetween = lookVec:Lerp(rightVec,math.random())
randomVecBetween = randomVecBetween.Unit -- lerping normalised vectors may not guarantee a normalised result, so we do it here.
-- This version should give you the best possible result, as we are generating a direction via changing rotation, rather changing position.

local cfA = CFrame.lookAt(Vector3.zero,newCF.LookVector) -- You could also swap "LookVector" and "RightVector" to get the right result
local cfB = CFrame.lookAt(Vector3.zero,newCF.RightVector)

local lerpedCF = cfA:Lerp(cfB,math.random())
local randomVecBetween = lerpedCF.RightVector -- This may be wrong, if so, change this to "lerpedCF.LookVector" or "lerpedCF.UpVector"

5 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.