OrbitCam and RawMouse

Hi new Processing forum. Here is an example of how to do raw mouse and a trackball type camera using matrices instead of using libraries / quaternions.

p5js version - https://www.openprocessing.org/sketch/550998
processingjs version - https://www.openprocessing.org/sketch/550454

/*
trackball type camera controls without libraries or quaternions
uses two matrices instead
also includes raw mouse via JOGL
*/

import com.jogamp.newt.opengl.GLWindow;

PMatrix3D acc, delta;
PVector camEye, camUp, camPitch;
PVector eye, up;
float sensitivity = 0.01;

boolean pointerLock;

void setup() {
  size(1280,720,P3D);
  noFill();
  stroke(255);
  perspective(
    HALF_PI,
    (float)width/height,
    0.001, 100000
  );

  acc = new PMatrix3D();
  delta = new PMatrix3D();

  camEye = new PVector(0, 0, 500);
  eye = camEye.copy();
  camUp = new PVector(0, 1, 0);
  up = camUp.copy();
  camPitch = new PVector(1, 0, 0);
}

void mouseMoved() {
  if(!pointerLock) return;

  float xx = (mouseX - width * 0.5);
  float yy = (mouseY - height * 0.5);

  eye = acc.mult(camEye.copy(), null);
  up = acc.mult(camUp.copy(), null);
  PVector pitch = acc.mult(camPitch.copy(), null);

  delta.rotate(xx*sensitivity, up.x, up.y, up.z);
  delta.rotate(yy*sensitivity, pitch.x, pitch.y, pitch.z);
  acc.preApply(delta);
  delta.reset();

  ((GLWindow)getSurface().getNative())
    .warpPointer(width / 2, height / 2);
}

void mouseClicked() {
  pointerLock = !pointerLock;
  if(pointerLock) {
    noCursor();
  } else {
    cursor();
  }
}

void draw() {
  background(0);

  camera(
    eye.x, eye.y, eye.z,
    0, 0, 0,
    up.x, up.y, up.z
  );

  box(100);
  translate(110, 0, 0);
  box(100);
  translate(-110, -110, 0);
  box(100);
}

3 Likes

Thank you for sharing this – and for providing both Processing(Java) and p5.js versions!

It is really useful that this simple code does not need a library dependency. Are you familiar with the peasycam library, and if so could you say how this code compares to its approach to implementing a “dead simple mouse driven camera”?

There’s also this “Rotating Cube” using pure 3D math, for Java Mode & p5js:


Originally from Khan’s Pjs:
https://KhanAcademy.org/computer-programming/3d-tutorial-4/1648921303

Based on: http://PeterCollingridge.AppSpot.com/3D-tutorial

1 Like

I think with this example it would still be possible to get gimbal lock – although it would probably be unlikely if you are only rotating it with the mouse – where with PeasyCam it is not.

Also PeasyCam does a bunch of stuff not included in this example like pan, zoom, rotate around look direction, lock rotation to one axis, reset position / zoom / rotation all automatically bound to mouse and keyboard controls.