I want my camera to following behind the player at all times. When the player turns to the left, I would expect the camera would move behind the player while remaining focused on the player.
My camera stays focused on the player. However, it does not rotate to stay behind the player.
I tried following the directions from here, and here. Neither of which seems to help.
Here's my code:
public class CameraFollow : MonoBehaviour
{
private GameObject player;
private GameObject mainCamera;
private Vector3 offset;
private float distance;
private Vector3 playerPrevPos;
private Vector3 playerMoveDir;
// Use this for initialization
private void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
mainCamera = GameObject.FindGameObjectWithTag("MainCamera");
//Calculate and store the offset value by getting the distance between the player's position and camera's position.
offset = transform.position - player.transform.position;
distance = offset.magnitude;
playerPrevPos = player.transform.position;
}
// Update is called once per frame
private void Update() { }
private void LateUpdate()
{
playerMoveDir = player.transform.position - playerPrevPos;
if (playerMoveDir != Vector3.zero)
{
playerMoveDir.Normalize();
transform.position = player.transform.position + offset;
transform.LookAt(player.transform.position);
transform.rotation = Quaternion.Lerp(transform.rotation, player.transform.rotation, Time.deltaTime * 1);
mainCamera.transform.position = player.transform.position + offset;
mainCamera.transform.LookAt(player.transform.position);
mainCamera.transform.rotation = Quaternion.Lerp(transform.rotation, player.transform.rotation, Time.deltaTime * 1);
playerPrevPos = player.transform.position;
}
}
}
I have done something a little different, per instructions from a online unity class. My main camera is a subobject of a rootobject, as shown in this picture.
I have attached image of the game with the yellow line showing which way the player is facing. The camera is facing in a different direction.
Any help would be appreciated.
Thnx
Matt
Follow-up from answers:
I cannot get either solution to work. @alejandrodlsp solution doesn't compile (I've added a comment to the answer explaining why). If I do not set offset
on Start (aka its always 0), then the camera rotates. The problem is that is at the feet the player and not behind like I wanted. Once I compute offset, then the camera never rotates behind the player.