Unity Main Camera Tracking Player

The following code can be used for the camera to follow the player in a platform type game developed in Unity..

public class CameraController : MonoBehaviour { public GameObject player; public float offset; private Vector3 playerPosition; public float offsetSmoothing; void Start() { } void Update() { playerPosition = new Vector3( player.transform.position.x, transform.position.y, transform.position.z ); if (player.transform.localScale.x > 0f) { playerPosition = new Vector3( player.transform.position.x + offset, transform.position.y, transform.position.z ); } else { playerPosition = new Vector3( player.transform.position.x - offset, transform.position.y, transform.position.z ); } transform.position = Vector3.Lerp( transform.position, playerPosition, offsetSmoothing * Time.deltaTime ); } }

The value to be assigned to offsetSmoothing is used for better camera smoothness..



You May Interest

GameObject Search By Unity Tag

Using the Unity Editor Device Simulator

Unity Visual Studio Debug Problem

Unity Exit Example

What is Unity NPC?