Hello! I’ve got my hands on a script and i can’t seem to figure out why the camera isn’t locking to the player. For example when i drop my player into the world the camera spawns behind the player but does not lock to the player. I have an empty gameobject inside the player that the “target” variable is assigned to in this script. I instantiate my player if anything has to do with that.
The problem is that if my player falls, the camera is still locked in the Y-position it has in the start.
IF! I hold the right mouse button though, there’s no problem at all with the camera, which seems weird to me. I would want the right-click “function” to stick the camera in that position, but i’m too bad to do that. Anyway, here’s the script
The script:
using UnityEngine;
using System.Collections;
public class PlayerCameraScript : MonoBehaviour {
public Transform target;
public float distance;
public float cameraHeight;
private Transform _myTransform;
float x;
float y;
float xSpeed = 250.0f;
float ySpeed = 120.0f;
float heightDamping = 2.0f;
float rotationDamping = 3.0f;
// Use this for initialization
void Start () {
target = GameObject.FindWithTag ("CameraFocus").transform;
if(target == null) {
Debug.Log("No target assigned for the camera");
}
_myTransform = transform;
CameraSetup();
}
void LateUpdate() {
if(target != null) {
if(Input.GetMouseButton(1)) {
x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
Quaternion rotation = Quaternion.Euler (y, x, 0);
Vector3 position = rotation * new Vector3(0.0f, 0.0f, -distance) + target.position;
_myTransform.rotation = rotation;
_myTransform.position = position;
}
else {
x = 0;
y = 0;
//Calculate the current rotation angles
float wantedRotationAngle = target.eulerAngles.y;
float wantedHeight = cameraHeight;
float currentRotationAngle = _myTransform.eulerAngles.y;
//Damp the rotation around the y-axis
currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
//Damp the height
cameraHeight = Mathf.Lerp(cameraHeight, wantedHeight, heightDamping * Time.deltaTime);
//Convert the angle into a rotation
Quaternion currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);
//Set the position of the camera to a distance behind target
_myTransform.position = target.position;
_myTransform.position -= currentRotation * Vector3.forward * distance;
//Set the height of the camera
_myTransform.position = new Vector3(_myTransform.position.x, cameraHeight, _myTransform.position.z);
}
}
}
public void CameraSetup() {
_myTransform.position = new Vector3(target.position.x, target.position.y + cameraHeight, _myTransform.position.z - distance);
_myTransform.LookAt(target);
}
}