Player rotates spastically on all axes when camera is turned
I've been trying for hours to debug an issue I'm having in a game I'm working on to no avail, so I figured I'd ask here. In the game the player is able to walk around a spherical planet and the camera adjusts so it always feels like you're on the top of the planet rather than hanging off the side or upside down. I achieve this effect using the following code:
using UnityEngine;
// Used to orientate the player based on their position on the planet
public class PlayerOrientation : MonoBehaviour
{
public GameObject activeBody;
CameraAiming cameraAiming;
Rigidbody rb;
Vector3 angles = new Vector3();
// Start is called before the first frame update
void Start()
{
cameraAiming = GetComponentInChildren<CameraAiming>();
rb = GetComponent<Rigidbody>();
}
// Fixed update is used for physics updates
void FixedUpdate()
{
// Set's the player's orientation based on their position on the active body
Vector3 upwards = transform.position - activeBody.transform.position;
angles.x = Mathf.Rad2Deg * Mathf.Atan(upwards.z / upwards.y);
angles.z = -Mathf.Rad2Deg * Mathf.Atan(upwards.x / upwards.y);
}
// Update is called once per frame
void Update()
{
// Sets rotation on the y-axis
angles.y += Input.GetAxis("Mouse X") * (cameraAiming.sensitivity / 5);
// Rotates the player around the local y-axis but the global z- and x- axes
rb.rotation = Quaternion.AngleAxis(angles.y, transform.up) *
Quaternion.AngleAxis(angles.z, Vector3.forward) *
Quaternion.AngleAxis(angles.x, Vector3.right);
}
}
That's code for c#, but I apologize that I'm not familiar enough with this site to format it. Basically that code works perfectly fine as long as the y rotation is between about -60 and 60 degrees, but once it goes outside that range it has a massive spasm. This video link demonstrates the issue I'm having, but I would strongly recommend against watching it if you are prone to seizures: https://imgur.com/a/8D2z3mR
I have noticed that if I set the rigidbody to kinematic and directly modify the transform's rotation rather than the rigidbody's that it works perfectly as intended, but the issue with this is that I don't have proper collision detection while it is kinematic. The following link is to an image of the normal rigidbody settings in the editor in case that has something to do with it: https://imgur.com/a/9r4dDZR
Any help is greatly appreciated!