Mathf.Cos having an issue at 90 and 270. Used with rotation of an object around 3 axis with mouse

Hi,

Thank you in advance for any assistance.

I am using the code below to make a cube rotate around all 3 axes following the position of the mouse when the right button is dragged. When the vertical rotation, around the x-axis, determined by the variable “yDeg” gets to 90 or 270 degrees it stops rotating. Swapping things out, guessing and checking, it only seems to have an issue when I use Mathf.Cos. Mathf.Sin seems to work fine, but of course doesn’t accomplish what I need.

It looks like it might be because of a change that occurs when the x axis rotation gets to 90. At 90 the y axis and z axis rotations suddenly adjust 180 degrees. Simply adding 180 degrees in that instance doesn’t seem to change the result. How do I deal with this issue?

    private int speed = 12;
    private float friction = .3f;
    private float lerpSpeed = 10.5f;
    private float xDeg;
    private float yDeg;
    private float zDeg;
    
    private Quaternion fromRotation;
    private Quaternion toRotation;
    	
    void Update () 
    {
    	if(Input.GetMouseButton(1)) 
    	{			
    		xDeg -= Input.GetAxis("Mouse X") * speed * friction;
    		yDeg += Input.GetAxis("Mouse Y") * Mathf.Cos (transform.eulerAngles.y * Mathf.PI / 180) * speed * friction;
		    zDeg += Input.GetAxis("Mouse Y") * Mathf.Sin (transform.eulerAngles.y * Mathf.PI / 180) * speed * friction;
    
    		toRotation = Quaternion.Euler(yDeg,xDeg,zDeg);
    	}
    
    	fromRotation = transform.rotation;
    	transform.rotation = Quaternion.Lerp(fromRotation,toRotation,Time.deltaTime  * lerpSpeed);
    }

Is there an issue with Mathf.Cos or is there something else I’m doing wrong?

Thank you.

The problem does not lie with Mathf.Cos, but with the fact that you’re building on transform.eulerAngles. As you aptly noticed, there are some strange things going on with rotation values viewed in euler angles. The Unity documentation also states that you should never build on euler angles incrementally. Instead, rotate the transform with fresh values, as such:

if (Input.GetMouseButton(1))
{
    Vector3 rotation = new Vector3();
    rotation.y = -Input.GetAxis("Mouse X") * speed * friction;
    rotation.x = Input.GetAxis("Mouse Y") * speed * friction;
    rotation.z = Input.GetAxis("Mouse Y") * speed * friction;

    toRotation *= Quaternion.Euler(rotation);
}

transform.rotation = Quaternion.Lerp(transform.rotation, toRotation, Time.deltaTime * lerpSpeed);

Turns out the answer was much simpler.

{
	void Update () 
	{
		if (Input.GetMouseButton(0))
		{
			transform.Rotate (new Vector3 ((Input.GetAxis("Mouse Y")* 200), (-Input.GetAxis("Mouse X")* 200), 0)* Time.deltaTime, Space.World);
		}
	}
}