Third-person camera controller - part 2
Let's write a script for your camera which will follow our main character as it walks. The camera will also be able to zoom in and zoom out.
Let's now make a C# script for our camera to follow the character as it moves. Go to the
Script
folder in the project window, right-click and selectCreate > C# Script
and name itCameraController
.Copy and paste this code into the
CameraController.cs
file.
xxxxxxxxxx
//using namespaces
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
​
public class CameraController : MonoBehaviour
{
public GameObject target;// reference to the target Object (so we can look at it when we are in normal play mode (not customizing))
public float zoomSpeed = 700;// // speed of zooming the camera in or out
//using the LateUpdate() event method which is called after the Update() event method
void LateUpdate()
{
//transform.LookAt() method is used to rotate a game object so that its forward vector points at another point
transform.LookAt(target.transform); // look at the target
var mouseScroll = Input.GetAxis("Mouse ScrollWheel");//// check how much mouse was scrolled (use for camera zooming)
​
if (mouseScroll != 0)// if mouseScroll value is not equal to 0
{
transform.Translate(transform.forward * mouseScroll * zoomSpeed * Time.deltaTime, Space.Self);//// zoom the camera in or out
}
}
}
Code Explanation:
The script is for your camera which will follow our main character as it walks. The camera will also be able to zoom in and zoom out.
Start: