Issues with Mathf.cos and transform.rotation

I’m using unity 2d engine and running into a problem that might have to do with radians. Using Unity’s mathf.cos and sin, the docs say it takes in a float using radians. I want to use the gameobject’s tranform.rotation.z as an input to mathf.cos. how would it work in the following example :

``````    void OnDrawGizmosSelected()
{
// Draw a semitransparent red cube at the transforms position
Gizmos.color = new Color(1, 0, 0, 0.5f);
float newX = 1.0f * Mathf.Cos(transform.rotation.z);
float newY = 1.0f * Mathf.Sin(transform.rotation.z);
Vector3 newPos = new Vector3(transform.position.x + newX, transform.position.y + newY, 0.0f);
Gizmos.DrawCube(newPos, new Vector3(0.33f, 0.33f, 0.33f));
}
``````

I am currently rotating a circle in the inspector at runtime and getting weird results for the cube placement. I want the cube to completely rotate around the circle.

`rotation.z` is NOT an angle of any kind, radian, degree, gradian, or otherwise.

`rotation.z` is an internal Quaternion term.

Perhaps you seek `rotation.eulerAngles.z` ?

Beware also of this:

All about Euler angles and rotations, by StarManta:

https://starmanta.gitbooks.io/unitytipsredux/content/second-question.html

Quaternion dumper if you insist on peeking inside the ugly parts:

https://discussions.unity.com/t/920939/13

And don’t forget to multiply by constants `Mathf.Rad2Deg` and `Mathf.Deg2Rad` to swap between radians and degrees.

2 Likes

rotation.eulerAngles.z * mathf.deg2rad works perfectly, thank you!

It’s probably easier to use `transform.forward` and `transform.right`. Those are precomputed arrows going 1 unit the object is facing, and 1 unit sideways. I think those are the end result of what you’re trying to get with Sin and Cos. I’m guessing you want something like `transform.position+transform.forward*1.5f;` (a point 1.5 units directly in front of whichever way you’re facing).

I like trig, and it feels like you’re really in control with it, but there’s almost nothing in Unity that isn’t better, faster and easier-to-read, using either built-ins or quaternion math.

3 Likes