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

Changing a Vector into a Unit Vector?

Asked by 6 years ago

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

Log in to vote
1
Answered by 6 years ago
Edited 5 years ago

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!

0
Thanks so much this helps alot! I never knew they had a built in function! TheFierceWaffle 64 — 6y
0
Pretty sure unit vectors have a length of 1 frostysubatomiczero 51 — 6y
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. LifeInDevelopment 364 — 6y
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! UnitVector 47 — 6y
Ad

Answer this question