I have tried to implement a basic camera movement around a third person character which is controlled by the mouse, however I get strange behavior and it’s been a while since I did this maths.
I have a camera it is not a child of the character the camera is supposed to follow the character but rotate relative to the scene. Therefore rotating the character should not affect the camera and vice-versa.
Here is what I have got so far (gameObject
is the camera):
public void Update() {
float yawAmount = Input.GetAxis ("Mouse X");
float pitchAmount = Input.GetAxis ("Mouse Y");
RotateCamera(yawAmount, -pitchAmount);
// position the camera
gameObject.transform.position = (camLocalPos + curTarget);
// look at target
gameObject.transform.LookAt (curTarget);
}
public void RotateCamera(float x, float y) {
yaw += x*0.1f;
pitch += y*0.1f;
if (pitch > maxPitch)
pitch = maxPitch;
if (pitch < minPitch)
pitch = minPitch;
UpdateCamera ();
}
private void UpdateCamera() {
camLocalPos.x = distance * Mathf.Cos(pitch) * Mathf.Sin(yaw);
camLocalPos.y = distance * Mathf.Sin(pitch) * Mathf.Sin(yaw);
camLocalPos.z = distance * Mathf.Cos(yaw);
}
It mostly works, but depending on which way the camera is facing it flips the pitch such that looking one way up is up and looking the other way up is down (and everything in between).
Can anyone point out the error please?
Update
I realised that I had the pitch and yaw the wrong way round it should be:
camLocalPos.x = distance * Mathf.Cos(yaw) * Mathf.Sin(pitch);
camLocalPos.y = distance * Mathf.Sin(yaw) * Mathf.Sin(pitch);
camLocalPos.z = distance * Mathf.Cos(pitch);
but changing this makes it worse! I’m 99% sure that the error is in the above three lines but I have been over and over it and cannot see anything wrong:
Update 2
Are the axes in the correct orientation?