Search code examples
pythonopenglglut

How to draw a rectangle perpendicular to a vector in OpenGL


I'm trying to draw a rectangle perpendicular to vector v:

glPushMatrix()
glTranslatef(v[0], v[1], v[2])
glBegin(GL_QUADS)
glVertex3f( -h, -h, 0)
glVertex3f( h, -h, 0)
glVertex3f( h, h, 0)
glVertex3f( -h, h, 0)
glEnd()

The resulting rectangle sits at the end of vector (I need this), how do I make it perpendicular to this vector?


Solution

  • If the vector v is a in view space, then the x axis points to the left, the y axis points up and z axis points out of the viewport.

    Calculate the longitude and latitude - see Geographic coordinate system:

    import math
    
    lenXY = math.sqrt(v[0]*v[0] + v[2]*v[2])
    lon   = math.atan2(v[0], v[2])
    lat   = math.atan2(v[1], -lenXY)
    

    Do a rotation around the x and y axis:

    glPushMatrix()
    glTranslatef(v[0], v[1], v[2])
    glRotatef(math.degrees(lon), 0, 1, 0)
    glRotatef(math.degrees(lat), 1, 0, 0)
    
    # [...]
    
    glPopMatrix()