Rotation in an if statement
I am fairly new to Unity and c# so please excuse my incompetence...
I am trying to add torque to my game object if the (based on the transform UI) angle is greater than say 35 degrees and also the corresponding negative degree. I have come to understand that the UI does not correspond with the angle values used in code, but it is the only basis I have.
I tried looking up how to do this and all I got was (for me) incomprehensible stuff about quaternions and Euler angles, but for the moment I don't have time to learn that in-depth, and I really just need to know what code to put in.
Answer by unity_ek98vnTRplGj8Q · Feb 12, 2020 at 04:49 AM
So the answer here varies a bit depending on what exactly you want to do, so let me make a few assumptions -
1. You are only rotating about the Z axis (x and y rotations will remain at 0)
2. You want to add torque when the magnitude of the rotation is greater than a certain value (that is you want to add torque regardless of the direction of the rotation
This is fairly straightforward. The only thing you need to know is that rotation.eulerAngles gives you the rotation values around each axis, and these values are between 0 and 360. It is correct that these values will not always correspond with the values in the UI.
//How much to rotate before torque is applied
float torqueThreshold = 35;
//Get rotation about the z axis
float zRotation = transform.rotation.eulerAngles.z;
//Adjust the values to between -180 and 180
while(zRotation > 180) zRotation -= 360;
//Take the absolute value to get the rotation magnitude
if(Mathf.Abs(zRotation) > torqueThreshold){
//Add torque
}
If you are rotating about more than one axis then this becomes a little bit more complicated. Also quaternions and euler angles can seem daunting when you don't know what they are or how they work, but in reality they are pretty simple to use (many people don't put in the time to learn how to use them correctly). If you have any questions about them then I can probably help you out. Once you understand how to use quaternions then any difficult rotations that you want to do in code suddenly become much easier.
Your answer
Follow this Question
Related Questions
problem of rotate joint of hands 0 Answers
Ambient Emitter inside a BoxCollider - Rotation not recognized 0 Answers
Why the subtracting compound assignment operator is used to ADD a angle in unity? 1 Answer
if the Android/ios device rotate (x) degrees do animation 0 Answers
Angle between objects taking in consideration their rotations? 0 Answers