Make the camera follow an object

Camera is designed for 3D (P3D). camera() / Reference / Processing.org

In 2D, “translate()” (and rotate) is the essence of the camera.

Here is a very simple example. The sketch is drawing a fixed platform and avatar around 0,0, but a moving “camera” can be toggled with the spacebar.

/**
 * 2D camera for platformer -- left/right moves, space toggles camera
 * 2019-04 Processing 3.4
 * https://discourse.processing.org/t/help-with-camera-function/10386
 */
int x;
boolean cameraOn = true;

void draw() {
  background(0);
  translate(width/2, height/2); // center the shot
  if(cameraOn) myCamera();
  platform();
  avatar();
}

void platform(){
  rectMode(CENTER);
  rect(0, 0, 70, 20);
}

void avatar(){
  if(keyPressed){
    if(keyCode==RIGHT) x++;  // move
    if(keyCode==LEFT) x--;
    if(x>35) x=-35;          // wrap around
    if(x<-35) x=35;
  }
  ellipse(x, -10, 10, 10);   // draw
}

// move the camera in a circle based on time
void myCamera(){
  translate(width/3 * sin(millis()*.001), height/3 * cos(millis()*.001));
}

void keyReleased(){
  if(key==' ') cameraOn = !cameraOn;
}

08%20AM

Notice that the platform is always drawn centered on 0,0. The “camera” is just an optional translate command that changes the frame of reference – the view – before the platform is drawn.

For a different example with vertical scrolling, see:

Again, it is just a translate command before drawing.