Skip to content

Player Camera

Alexander Johnson edited this page Aug 28, 2024 · 2 revisions

Overview

The player camera follows the player character during game play, ensuring that they are focused in the center of the screen. The camera can be zoomed in or out by scrolling the mouse wheel up or down, respectively. This allows for players to choose the magnification level which best suits their game play.


CameraComponent

The camera is attached to the Player entity using the CameraComponent class. This class has an update method which changes the position of the camera to equal to equal the center position of the player's character sprite.

@Override
public void update() {
    Vector2 position = entity.getCenterPosition();
    if (!lastPosition.epsilonEquals(entity.getCenterPosition())) {
        camera.position.set(position, 0f);
        lastPosition = position;
        camera.update();
    }
  }

An example showing how the game camera follows the player is shown below.

Player cam


CameraZoomComponent

The camera zoom is handled by a separate component called a CameraZoomComponent. This component listens for a cameraZoom event which is triggered whenever the player scrolls the mouse wheel. Upon firing, the zoom method is called in the component class which is responsible for zooming the camera in or out using the resize method in the camera component.

public void zoom(float amountX, float amountY) {
    Camera camera = cameraComponent.getCamera();
    // Calculate new dimensions for camera viewport
    int screenWidth = Gdx.graphics.getWidth();
    int screenHeight = Gdx.graphics.getHeight();
    float gameWidth = camera.viewportWidth;
    gameWidth = gameWidth + ZOOM_AMOUNT * amountY;
    // Ensure that camera doesn't exceed zoom amount
    gameWidth = Math.clamp(gameWidth, minZoom, maxZoom);
    cameraComponent.resize(screenWidth, screenHeight, gameWidth);
}

For this reason, a CameraZoomComponent can only be attached to an entity which also has a CameraComponent.

There are three main parameters in the zoom methods:

  • ZOOM_AMOUNT: the amount by which to zoom in or out
  • minZoom: the maximum amount that the camera can zoom in
  • maxZoom: the maximum amount that the camera can zoom out

An example showing how the camera zoom responds to user input is shown below.

Player cam - zoom


Planned Features

One planned feature for the camera is to make it behave differently when a player reaches the world border. Currently the player can also see unrendered map because the camera always focuses the player in the center of the screen. It would improve game play experience to make the camera "detach" when the player character reaches a world border so as to not show unrendered terrain, and "reattach" when the player moves away.

Clone this wiki locally