Camera
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
Sometimes the desired behavior is for the camera to trail behind the follow target. The simplest implementation for this behavior is to use interpolation to move the camera a percentage of the way towards the target each frame.
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; }
Note that there is a check for the camera being at a minimum distance from the target which snaps the camera into its equilibrium position.
Spring Damper
Adding camera physics helps to smooth out the motion of the camera, and the simplest form of camera physics is a spring damper system. The following code simulates a critically damped spring damper system.
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 Vector3 AccelerationSpring = (FollowRate * FollowRate / 4) * d; // the damping acceleration which scales opposite the velocity of the camera Vector3 AccelerationDamping = -1 * FollowRate * CameraVelocity; Vector3 CameraAcceleration = AccelerationSpring + AccelerationDamping; // apply acceleration to velocity CameraVelocity += CameraAcceleration * dt; // settle if both velocity and acceleration are near zero if (CameraVelocity.DistanceSquared() < 1 && CameraAcceleration.DistanceSquared() < 1) { CameraVelocity = Vector2.Zero; CameraPosition = FollowTarget + FollowOffset; } // apply velocity to position else { CameraPosition += CameraVelocity * dt; } }