Trackball camera

This camera rotates about an object and can zoom in and out.

(This code assumes you have the Shape, Group and box classes)

/* a trackball camera that spins around an object */
 
import processing.opengl.*;
import javax.media.opengl.*; 
 
Group graph;
 
// variables for the current camera rotation and zoom
PVector cameraRotation;
float zoom;
 
 
void setup()
{
   size(600, 600, OPENGL); 
 
   cameraRotation = new PVector(0, 0);
   zoom = -200.0f;
 
  graph = new Group();
  Box box1 = new Box();
  box1.setPosition(new PVector(0, 0, 0));
  box1.setRotation(new PVector(0, 45, 0));
  box1.setScale(new PVector(200, 50, 100));
  graph.addShape(box1);
 
}
 
void draw()
{
   background(255);
   strokeWeight(5);
 
 
 
  lights();
 
  // camera control
 
  // w and s zoom
 
  if (keyPressed)
  {
   if (key == 'w')
     zoom += 10;
   if (key == 's')
     zoom -= 10;    
  }
 
  // the mouse spins the object around 
  if (mousePressed)
  {
    cameraRotation.x += -float(mouseY-pmouseY);
    cameraRotation.y += float(mouseX-pmouseX);
  }
 
  PGraphicsOpenGL pgl = (PGraphicsOpenGL) g;  // g may changes
  GL gl = pgl.beginGL();  // always use the GL object returned by beginGL
  gl.glEnable(gl.GL_LIGHTING);
  gl.glEnable(gl.GL_LIGHT0); 
 
  // create the projection matrix
  // I am using glFrustum to get a perspective view
  // comment the glFrustum line out and uncomment the
  // glOrtho line to get an orthographic view
  gl.glMatrixMode(gl.GL_PROJECTION);
  gl.glLoadIdentity();
  //gl.glOrtho(-400, 400, -400, 400, -10, 1000);
  gl.glFrustum(-10.0f, 10.0f, -10.0f, 10.0f, 10.0f, 1000.0f);
 
  // work on the camera transforms
  gl.glMatrixMode(gl.GL_MODELVIEW);
  // set the transform to the identity (do nothing)
  gl.glLoadIdentity();
 
  // use gluLook at to get it looking along z and using y as up
  pgl.glu.gluLookAt(0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
 
  // these are the camera transforms
  // in this order they move the camera and
  // rotate the object
 
  // translate to zoom 
  gl.glTranslatef(0.0f, 0.0f, -zoom);
  // use one rotation each for x and y object rotation
  gl.glRotatef(cameraRotation.x, 1, 0, 0);
  gl.glRotatef(cameraRotation.y, 0, 1, 0);
 
  graph.update();
 
  graph.draw(gl);
 
 
  pgl.endGL();
}
PDF    Send article as PDF to