Keyboard and camera

Back to index

The function

glu.gluLookAt(cameraX, cameraY, cameraZ, lookAtX, lookAtY, lookAtZ, upX, upY, upZ);

controls the position and orientation of the 'camera' through which we view things.

In this example we will use the keyboard to control the camera position.

Keyboard use

We can enable keyboard use if we -

Declare some class to implement the KeyListener interface

Implement the KeyListener methods

Set this as the listener

That is..

public class Keyboard implements GLEventListener, KeyListener {

  

then

public void keyPressed(KeyEvent e) {
        switch (e.getKeyCode()) {
            case KeyEvent.VK_PAGE_UP:
                .. what we want to do
                break;
            case 
		..       
        }
    }

    public void keyReleased(KeyEvent e) {
    }

    public void keyTyped(KeyEvent e) {
    }

and

public void init(GLAutoDrawable gLDrawable) {
        final GL gl = gLDrawable.getGL();

	.. usual things

        gLDrawable.addKeyListener(this);
    }

Example

We will control the camera position with the keyboard. So we declare 3 attributes for this:

public class Keyboard implements GLEventListener, KeyListener {

    static Animator animator = null;
    private GLU glu = new GLU();    
    private float cameraX = 0.0f;
    private float cameraY = 0.0f;
    private float cameraZ = 5.0f;

and in display we say:

public void display(GLAutoDrawable gLDrawable) {
        final GL gl = gLDrawable.getGL();
        gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
        gl.glLoadIdentity();// Reset The View
        glu.gluLookAt(cameraX, cameraY, cameraZ, 0, 0, 0.0, 0.0, 1.0, 0.0);
        gl.glBegin(GL.GL_QUADS);
        gl.glNormal3f(0.0f, 0.0f, 1.0f);
        gl.glVertex3f(-1.0f, -1.0f, 1.0f);
        gl.glVertex3f(1.0f, -1.0f, 1.0f);
        gl.glVertex3f(1.0f, 1.0f, 1.0f);
        gl.glVertex3f(-1.0f, 1.0f, 1.0f);
        gl.glEnd();
    }

and we alter these attributes like:

public void keyPressed(KeyEvent e) {
        switch (e.getKeyCode()) {

            case KeyEvent.VK_PAGE_UP:
                cameraZ -= 0.05f;
                break;
            case KeyEvent.VK_PAGE_DOWN:
                cameraZ += 0.05f;
                break;
            case KeyEvent.VK_UP:
                cameraY -= 0.05f;
                break;
            case KeyEvent.VK_DOWN:
                cameraY += 0.05f;
                break;
            case KeyEvent.VK_RIGHT:
                cameraX += 0.05f;
                break;
            case KeyEvent.VK_LEFT:
                cameraX -= 0.05f;
                break;
            case KeyEvent.VK_ESCAPE:
                animator.stop();
                System.exit(0);
                break;
        }
    }

So we can move around and see:

keyboard