Reputation: 227
I am currently implementing a radio in Unity for Oculus. Player can twist the knob to change volume. However, either eulerangle or rotation cannot return a unique value while turning in 360 degrees.
And below code has the same problem with eulerangle.
void Start ()
{
oldRight = Vector3.right;
angle = 0.0f;
}
void Update ()
{
Vector3 right = transform.right;
float tempAngle = Vector3.SignedAngle(oldRight,right,transform.forward);
if (right.y < oldRight.y)
{
angle += tempAngle;
}
else
{
angle -= tempAngle;
}
oldRight = right;
}
Upvotes: 0
Views: 745
Reputation: 4249
First of all, we don't know what's the relation between the radio game object and the knob game object, and that matters.
I'll make an example in order to show how you can get the rotation of the knob regardless of that relation.
In the image below, the radio is the cube, with its transform reset all to 0.
This is the cylinder which acts as the knob:
The important part here is that I rotated and placed the cylinder such that the X axis of the transform is parallel to the X axis of the cube.
And here is the script that rotates the cylinder and reports the angle of such rotation:
using UnityEngine;
public class RotateKnob : MonoBehaviour {
public float m_Speed;
void Update() {
if (Input.GetKey(KeyCode.RightArrow)) {
transform.Rotate(Vector3.up, Time.deltaTime * m_Speed, Space.Self);
}
if (Input.GetKey(KeyCode.LeftArrow)) {
transform.Rotate(Vector3.down, Time.deltaTime * m_Speed, Space.Self);
}
var angle = Vector3.SignedAngle(transform.right, transform.parent.right, transform.up);
Debug.Log(angle);
}
}
Notice how the rotation is done relative to the Y axis and Space.Self
.
The angle
is taken relative to the Y axis of the cylinder (which is the axis around which we rotate the cylinder), thus transform.up
as the SignedAngle
third parameter, and ofc we measure the angle between the transform.right
and the transform.parent.right
(the transform.right
of the cube that childs the cylinders).
With this code you don't have to worry about the transform of the cube in the world, the result will always be relative to the cube when rotating the cylinder.
Please do remember that the angle
will be reported in the range [-180,180]
and not [0,360]
.
Upvotes: 1
Reputation: 15941
If you want XYZ angles (and not a quaternion),
transform.rotation.eulerAngles
Upvotes: 1