- Home /
Camera cuts to behind player as I rotate around
I have been following this tutorial series but have a problem with the camera that I don't understand. I'm a beginner with Unity so I'm pretty lost going off script from the tutorial. Here is a screen recording of what's happening in my game. As I rotate my mouse around my character, the camera resets to looking behind my character. I can't pinpoint any exact degrees or axes this occurs on as it seems kind of random.
This is the camera code I have so far:
public class CameraController : MonoBehaviour
{
public Transform target;
public Vector3 offset;
public bool useOffsetValues;
public float rotateSpeed;
public Transform pivot;
public float maxViewAngle;
public float minViewAngle;
public bool invertY;
// Start is called before the first frame update
void Start()
{
if(!useOffsetValues){
offset = target.position - transform.position;
}
pivot.transform.position = target.transform.position;
// pivot.transform.parent = target.transform;
pivot.transform.parent = null;
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void LateUpdate()
{
pivot.transform.position = target.transform.position;
// get x pos of mouse and rotate the target
float horizontal = Input.GetAxis("Mouse X") * rotateSpeed;
pivot.Rotate(0, horizontal, 0);
// get y pos of mouse and rotate the pivot
float vertical = Input.GetAxis("Mouse Y") * rotateSpeed;
// pivot.Rotate(-vertical, 0, 0);
if(invertY){
pivot.Rotate(vertical, 0, 0);
}else{
pivot.Rotate(-vertical, 0, 0);
}
// limit up/down camera rotation
if(pivot.rotation.eulerAngles.x > maxViewAngle && pivot.rotation.eulerAngles.x < 180f){
pivot.rotation = Quaternion.Euler(maxViewAngle, 0, 0);
}
if(pivot.rotation.eulerAngles.x > 180f && pivot.rotation.eulerAngles.x < (360f + minViewAngle)){
pivot.rotation = Quaternion.Euler(360f + minViewAngle, 0, 0);
}
// move camera based on rotation of target and original offset
float desiredYAngle = pivot.eulerAngles.y;
float desiredXAngle = pivot.eulerAngles.x;
Quaternion rotation = Quaternion.Euler(desiredXAngle, desiredYAngle, 0);
transform.position = target.position - (rotation * offset);
// transform.position = target.position - offset;
if(transform.position.y < target.position.y){
transform.position = new Vector3(transform.position.x, target.position.y - 0.5f, transform.position.z);
}
transform.LookAt(target);
}
}
Thanks for the help!!
Answer by marck_ozz · Jan 26, 2021 at 06:34 AM
Hello
You have basically the same code except for;
// pivot.transform.parent = target.transform;
pivot.transform.parent = null;
If you are following exactly the same steps, you have to have the same code, if for some reason your "pivot" does not have a parent, you have to change the code in order to make the rotation around that pivot object.
That code will not work the same way with different "patent-child" objects.