4.1 Processing Basic 3D

There are five render modes you can set in the size() function when you setup your sketch. P3D enables a 3D sketch environment.

void setup() {
  size(1000, 500, P3D);
}

In order to navigate the 3D enivronment we will create a simple camera function that converts changes in the mouse’s X position into Y rotation and changes in the mouse’s Y position into X Rotation.

///camera varibles
int oldx = mouseX;
int oldy = mouseY;
float rotx = 0;
float roty = 0;

void setup() {
  size(1000, 500, P3D);
}

void draw(){
  background(0);
  cam();
  fill(255);
  rectMode(CENTER);
  rect(0,0,200,200);
}

void cam() {
  //get the current mouse position for x and y
  int newx = mouseX;
  int newy = mouseY;

  //Move everything to the center of the sketch 
  //so the rotation is around the center
  translate(width/2, height/2);

  //rotate sketch 
  rotateY(rotx);
  rotateX(roty);

  //if the mouse is pressed then the difference between 
  //the old and new mouse position is added to the 
  //curent rotation in both axes
  if ((mousePressed == true)) {
    rotx = rotx + (oldx-newx)/50.0;
    roty = roty + (oldy-newy)/50.0;
  }

  //replace old position valuesto the new ones
  oldx = newx;
  oldy = newy;
}

To zoom in and out we will adjust the translation of the sketch on the Z axis using the mouse wheel. The mouseWheel() is only called when the mouse wheel is scrolled.

void mouseWheel(MouseEvent event) {
  float e = event.getCount();
  zcam = zcam - e*5;
}

Overall sketch:

///camera varibles
int oldx = mouseX;
int oldy = mouseY;
float rotx = 0;
float roty = 0;
float zcam = 0;

void setup() {
  size(1000, 500, P3D);
}

void draw(){
  background(0);
  cam();
  fill(255);
  rectMode(CENTER);
  rect(0,0,200,200);
}

void cam() {
  int newx = mouseX;
  int newy = mouseY;
  translate(width/2, height/2,zcam);
  rotateY(rotx);
  rotateX(roty);
  //rotateZ(PI);
  if ((mousePressed == true)) {
    rotx = rotx + (oldx-newx)/50.0;
    roty = roty + (oldy-newy)/50.0;
  }
  oldx = newx;
  oldy = newy;
}

void mouseWheel(MouseEvent event) {
  float e = event.getCount();
  zcam = zcam - e*5;
}