Fixed Position Camera with Rotation

This camera doesn’t move but you can rotate it with the mouse.

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

/* simple camera positioning with rotation */
 
 
import processing.opengl.*;
import javax.media.opengl.*; 
 
Group graph;
 
// keep a variable for the camera rotation
PVector cameraRotation;
 
 
void setup()
{
   size(600, 600, OPENGL); 
 
   cameraRotation = new PVector(0, 0);
 
 
  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);
 
  Box box2 = new Box();
  box2.setPosition(new PVector(-300, 0, 0));
  box2.setScale(new PVector(100, 100, 100));
  graph.addShape(box2);
 
  Box box3 = new Box();
  box3.setPosition(new PVector(300, 0, 0));
  box3.setScale(new PVector(100, 100, 100));
  graph.addShape(box3);
 
}
 
 
void draw()
{
   background(255);
   strokeWeight(5);
 
 
  lights();
 
  // camera control
 
  // the mouse rotates the camera
  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();
 
  // rotate the camera
  gl.glRotatef(cameraRotation.x, 1, 0, 0);
  gl.glRotatef(cameraRotation.y, 0, 1, 0);
  // position the camera in a fixed position 
  // back along the z axis
  gl.glTranslatef(0.0f, 0.0f, -500.0f);
 
  graph.update();
 
  graph.draw(gl);
 
 
  pgl.endGL();
}
PDF    Send article as PDF to