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

Using the Unity Editor Device Simulator

Using Unity Editor Black Theme

Running Your Unity Project From Any Visual Studio You Want

Finding Unity SDK Path

How to Install Unity UI Toolkit Package ?