Search code examples
pythonopenglpyglet

opengl won't render desired output after switching from glTranslatef to gluLookAt


I have trouble to get gluLookAt working. I have the following code which works as expected using glTranslatef:

import pyglet 
from pyglet.gl import *

window = pyglet.window.Window() 

def draw_square():
    glBegin(GL_QUADS)
    glVertex3f(0, 0, 0.0)
    glVertex3f(100, 0, 0.0)
    glVertex3f(100, 100, 0.0)
    glVertex3f(0, 100, 0.0)
    glEnd()

def on_draw(): 
    window.clear() 
    draw_square()

from pyglet.window import key
@window.event
def on_key_press(symbol, modifiers):
    SHIFT_X_BY = 5.5
    if symbol == key.LEFT:
        glTranslatef(-SHIFT_X_BY, 0.0, 0.0)
    elif symbol == key.RIGHT:
        glTranslatef(SHIFT_X_BY, 0.0, 0.0)
    elif symbol == key.UP:
        glTranslatef(0.0, SHIFT_X_BY, 0.0)
    elif symbol == key.DOWN:
        glTranslatef(0.0, -SHIFT_X_BY, 0.0)

window.on_draw = on_draw
pyglet.app.run()

Now, instead of using glTranslatef I thought I can just shift the camera. I modified the code to call gluLookAt instead:

import pyglet 
from pyglet.gl import *

window = pyglet.window.Window(resizable=True)

def draw_square():
    glBegin(GL_QUADS)
    glVertex3f(0, 0, 0.0)
    glVertex3f(100, 0, 0.0)
    glVertex3f(100, 100, 0.0)
    glVertex3f(0, 100, 0.0)
    glEnd()

def on_draw(): 
    window.clear() 
    draw_square()


pos = {'x': 0, 'y': 0, 'z': 0}

from pyglet.window import key
@window.event
def on_key_press(symbol, modifiers):
    global pos
    SHIFT_X_BY = 5.5
    if symbol == key.LEFT:
        pos['x'] = pos['x'] + SHIFT_X_BY
    elif symbol == key.RIGHT:
        pos['x'] = pos['x'] - SHIFT_X_BY
    elif symbol == key.UP:
        pos['y'] = pos['y'] + SHIFT_X_BY
    elif symbol == key.DOWN:
        pos['y'] = pos['y'] - SHIFT_X_BY

    gluLookAt(pos['x'], pos['y'], pos['z'], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);

window.on_draw = on_draw
pyglet.app.run()

However, if I press one of the arrow keys now, the square just disappears. What am I doing wrong with calling gluLookAt?

EDIT this following on_draw() function doesn't work either (I just get a black screen):

def on_draw(): 
    glLoadIdentity()
    gluLookAt(pos['x'], pos['y'], pos['z'], 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)
    draw_square()

Solution

  • gluLookAt takes 3 types of vectors: "eye", "center" and "up".

    The eye is where you look from, center where you look at and the up vector is used to tell the cam how it is "opened". Typically you set up to 0,1,0:

    gluLookAt(pos['x'], pos['y'], pos['z'], 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);

    http://pyopengl.sourceforge.net/documentation/manual/gluLookAt.3G.html