Site Tools


Calculating a Perpendicular Vector

Developer: RhinoScript
Summary: Demonstrates how to calculate a perpendicular vector using RhinoScript.

Question

Does RhinoScript have a method to return a vector that is perpendicular to a given vector?

Answer

No. But it is possible to write your own function. The following sample RhinoScript demonstrates how to calculate a perpendicular vector.

 Option Explicit
 
 ' Description
 '   Set a vector to be perpendicular to another vector.
 ' Parameters
 '   v [in/out] - a unitized vector to set.
 ' Returns
 '   True or False indicating success or failure. 
 Function VectorPerpendicularTo( ByRef v )
 
   Dim i, j, k, a, b
   k = 2
 
   If Abs(v(1)) > Abs(v(0)) Then
     If Abs(v(2)) > Abs(v(1)) Then
       ' |v(2)| > |v(1)| > |v(0)|
       i = 2
       j = 1
       k = 0
       a = v(2)
       b = -v(1)
     ElseIf Abs(v(2)) >= Abs(v(0)) Then
       ' |v(1)| >= |v(2)| >= |v(0)|
       i = 1
       j = 2
       k = 0
       a = v(1)
       b = -v(2)
     Else
       ' |v(1)| > |v(0)| > |v(2)|
       i = 1
       j = 0
       k = 2
       a = v(1)
       b = -v(0)
     End If
   ElseIf Abs(v(2)) > Abs(v(0)) Then
     ' |v(2)| > |v(0)| >= |v(1)|
     i = 2
     j = 0
     k = 1
     a = v(2)
     b = -v(0)
   ElseIf Abs(v(2)) > Abs(v(1)) Then
     ' |v(0)| >= |v(2)| > |v(1)|
     i = 0
     j = 2
     k = 1
     a = v(0)
     b = -v(2)
   Else
     ' |v(0)| >= |v(1)| >= |v(2)|
     i = 0
     j = 1
     k = 2
     a = v(0)
     b = -v(1)
   End If
 
   v(i) = b
   v(j) = a
   v(k) = 0.0
 
   If a <> 0.0 Then
     VectorPerpendicularTo = True
   Else
     VectorPerpendicularTo = False
   End If
 
 End Function

You can test the above function as follows:

 Sub Test
   Dim v, b
   v = Rhino.VectorUnitize( Array(1,1,0) )
   b = VectorPerpendicularTo(v)
   MsgBox Rhino.Pt2Str( v )
 End Sub


developer/scriptsamples/vectorperpendicularto.txt ยท Last modified: 2015/09/14 (external edit)