Camera Controller – Third person camera
Below is a simple third-person camera script for Unity. This script allows the camera to follow the player smoothly and provides basic user-friendly features like adjusting the distance of the camera from the player and setting the height at which the camera follows. This script is written in C# and is designed for learners with basic knowledge of programming.
ThirdPersonCamera.cs
using UnityEngine;
// This script provides a third person camera that follows the player.
public class ThirdPersonCamera : MonoBehaviour
{
public Transform player; // Player's transform to follow
public float smoothing = 5f; // Speed of the camera's follow
public Vector3 offset = new Vector3(0f, 2f, -5f); // Offset of the camera relative to the player
void FixedUpdate()
{
// Target position is the player's position plus the offset
Vector3 targetCamPos = player.position + offset;
// Smoothly interpolate between the camera's current position and the target position
transform.position = Vector3.Lerp(transform.position, targetCamPos, smoothing * Time.deltaTime);
// Always look at the player
transform.LookAt(player);
}
}
Instructions for Use:
- Create the Script:
- Open Unity and in your project’s Assets folder, right-click and choose Create > C# Script.
- Name the script
ThirdPersonCamera
.
- Attach the Script:
- Drag the script onto your main camera in the scene.
- Configure the Script:
- Click on the camera and, in the Inspector window, you should see the
ThirdPersonCamera
script attached. - Drag the player’s character model (or the relevant GameObject) to the
Player
field in the script component. - Set the
Smoothing
value to adjust how quickly the camera follows the player. A higher number makes the camera more responsive. - Adjust the
Offset
to change the camera’s position relative to the player. This lets you position the camera above, behind, or to the side of the player as needed.
- Click on the camera and, in the Inspector window, you should see the
- Test the Game:
- Enter Play mode in Unity to test the camera’s behavior. Ensure the camera smoothly follows the player and that the offset and smoothing provide a good view of the character and environment.
This script is a basic starting point for a third-person camera system. As you get more comfortable with Unity and C#, you can expand on this script with additional features like camera collision detection, more complex smoothing functions, or dynamic offset adjustments based on gameplay elements.