Camera

From C# Gamedev Wiki
Revision as of 18:47, 9 June 2024 by Winkio (talk | contribs)

A camera is an object with functionality that supports viewing the game world from a specific position and orientation. Cameras can be fixed in place, or move dynamically, and many games have sophisticated camera systems that include collision and physics.

Follow

One of the most common behaviors implemented on dynamic cameras is the ability to follow a target, often the player.

Rigid Follow

The simplest implementation to achieve follow behavior is to rigidly lock your camera to the follow target. This was often done with early 2D games, where the camera would keep the player in the center of the screen at all times, unless the camera hit the scroll boundary of the map.

Vector3 CameraPosition;
Vector3 FollowTarget;
Vector3 FollowOffset = Vector3.Zero;

void Update(float dt)
{
    CameraPosition = FollowTarget + FollowOffset;
}

Interpolation

Vector3 CameraPosition;
Vector3 FollowTarget;
Vector3 FollowOffset = Vector3.Zero;
// FollowRate must be greater than zero.
float FollowRate = 2.0f;

void Update(float dt)
{
    // get vector to desired location
    var d = FollowTarget + FollowOffset - CameraPosition;
    var dsq = d.LengthSquared();
    CameraPosition += dsq > 1 ? d * FollowRate * dt : d;
}

Spring Damper

Vector3 CameraPosition;
Vector3 CameraVelocity;
Vector3 FollowTarget;
Vector3 FollowOffset = Vector3.Zero;
// FollowRate must be greater than zero.
float FollowRate = 2.0f;

void Update(float dt)
{
    // get vector to desired location
    var d = FollowTarget + FollowOffset - CameraPosition;
    // Calculate the acceleration of the camera.  This will be the sum of two terms:
    // the spring acceleration which scales with distance from the target
    Vector2 AccelerationSpring = (FollowRate * FollowRate / 4) * d;
    // the damping acceleration which scales opposite the velocity of the camera
    Vector2 AccelerationDamping = -1 * FollowRate * CameraVelocity;
    Vector2 CameraAcceleration = AccelerationSpring + AccelerationDamping;
    // apply acceleration to velocity
    CameraVelocity += CameraAcceleration * dt;
    // round velocity to zero if both velocity and acceleration are near zero
    if (CameraVelocity.DistanceSquared() < 1 && CameraAcceleration.DistanceSquared() < 1)
        CameraVelocity = Vector2.Zero;
    // apply velocity to position
    CameraPosition += CameraVelocity * dt;
}