Camera following a certain point

I have begun making a game, and I need the camera centered on the player. Currently I have tried transforming the coordinate system without luck, and I am not sure about what method I should use to make the camera move with the player. I am using Python

If you want your player to be the center of your camera, the easiest way to do that would to translate your terrain to be relative to your player’s position. Which could be something like this:

In the example, as the player moves “up”, the terrain or anything else will move down. If the player would be to move “left”, the terrain would move to the right, etc. So basically, the terrain moves in the opposite direction the players moving in. Here’s a small example:

float playerX = 0;
float playerY = 0;

float object1X;
float object1Y;
float object2X;
float object2Y;
float object3X;
float object3Y;

void setup() {
  size(400, 400);
  object1X = random(width);
  object1Y = random(height);
  object2X = random(width);
  object2Y = random(height);
  object3X = random(width);
  object3Y = random(height);
}

void draw() {
  noStroke();
  background(255);
  fill(255, 0, 0); // Fill red
  ellipse(width/2, height/2, 15, 15); // The player
  
  pushMatrix();
  
  translate(-playerX,-playerY); // Negative, as it moves in the opposite direction
  
  fill(0); // Fill black
  ellipse(object1X, object1Y, 15, 15); // Object 1
  ellipse(object2X, object2Y, 15, 15); // Object 2
  ellipse(object3X, object3Y, 15, 15); // Object 3
  popMatrix();
  
  // Use array keys to control player's position
  if(keyCode == UP && keyPressed) {
    playerY--; 
  }
  if(keyCode == DOWN && keyPressed) {
    playerY++;
  }
  if(keyCode == LEFT && keyPressed) {
    playerX--; 
  }
  if(keyCode == RIGHT && keyPressed) {
    playerX++;
  }
}

1 Like

Hello @danablend!
You can use the camera() function to set the position of your camera (need to be in P3D mode). Check out the reference for it here. By default the camera is set to:

camera(width/2.0, height/2.0, (height/2.0) / tan(PI*30.0 / 180.0), 
       width/2.0, height/2.0, 0, 
       0, 1, 0)

You can replace it with your player position like so:

camera(player.x, player.y, height/2 / tan(PI*30.0 / 180.0), 
       player.x, player.y, 0, 
       0, 1, 0)
3 Likes