You can accomplish this by adding the two vectors together and taking the unit of that vector.
Note: The following works when the vectors are perpendicular, as well as any case other than the special cases. You will have to do additional checks if you need to verify that the vectors are perpendicular before using this method.
1 | local Vector 1 = Vector 3. new( 0 , 1 , 0 ) |
2 | local Vector 2 = Vector 3. new( 0 , 0 , 1 ) |
4 | local NewVector = (Vector 1 + Vector 2 ).Unit |
Special Case
Certain vector combinations, such as adding zero vectors and vectors looking in opposite directions, are impossible to find the unit of. Attempting to do so will return:
1 | Vector 3. new(NaN,NaN,NaN) |
This can cause parts to do strange things such as disappearing, therefore it is important to check if your vector is NaN (Not a Number) before you use it. You can do this with the following:
1 | local ImpossibleVector = Vector 3. new( 0 , 0 , 0 ).Unit |
3 | ImpossibleVector = ImpossibleVector.X = = ImpossibleVector.X and ImpossibleVector or Vector 3. new( 0 , 0 , 0 ); |
Because NaN is the only number that does not equal itself (NaN ~= NaN), you can check if a component of the vector is equal to itself. In line 2 I check if the X component of the vector is equal to iself, returning the vector if it is, if not returning a zero vector.
Special cases that result in NaN vector.
1 | Vector 3. new( 0 , 0 , 0 ) + Vector 3. new( 0 , 0 , 0 ) |
2 | Vector 3. new( 0 , 1 , 0 ) + Vector 3. new( 0 ,- 1 , 0 ) |