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

Changing a Vector into a Unit Vector?

Hi there I am trying to turn a raycast into multiple segments. I was looking online an stuff... I guess I need to divide it's xyz's by its magnitude(length). But how would I do that in ROBLOX or in computers in general? The raycast is going to be shot in different directions every time, so how would I calculate that? I am guessing I need divide XYZs by length using variables, but where would I get the XYZs from? Thank you.

1 answer

✓ Accepted answer

If you would like to convert a vector into me, you can divide it by it's own magnitude. Dividing a vector by it's magnitude results in a unit vector, which is defined as direction with a length of one. This is useful in situations where you want to define the magnitude of the vector yourself for things like speed, force, etc. Take the following code for example:

local vecU = Vector3.new(0,0,0)
local vecH = Vector3.new(10,10,10)

local function getUnitVector(vec)
	return vec/vec.Magnitude
end

print( getUnitVector(vecH - vecU) )

This is how it would normally be done. For convenience, ROBLOX provides a property of all vectors called Unit, which does this calculation for us. The following code would do the same as above:

print( Vector3.new(x, y, z).Unit )

Let me know if you have any questions!

4 comments

0

Thanks so much this helps alot! I never knew they had a built in function!

0

Pretty sure unit vectors have a length of 1

0

"direction without length" isn't an accurate description of a unit vector, a unit/normalised vector has a magnitude of 1. This does however make it easier to perform calculations where only the direction of a vector is needed.

0

You are both absolutely right! I suppose the reason I said it has no length, which is untrue, is because any unit vector multiplied by a scalar will have the length of that scalar. I was most likely thinking about addition of two vectors, instead of multiplication of a vector and a scalar. Thanks for the correction!

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