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

Checking If Unity GameObject Has Child Object

What is Unity Asset Store?

What is Unity IL2CPP ?

What is Unity Sprite ?

How to Install Unity UI Toolkit Package ?