- Home /
Quaternions incorrect?
Hi, I'm trying to program doors that open slightly when you scroll the mousewheel around, and my door gets rotated on its side?
using UnityEngine;
using System.Collections;
public class BDXDoorScript : MonoBehaviour
{
private float MaxRotation = 90f;
private float MinRotation = -90f;
private float RotateAmount = 20;
public Quaternion DoorRotation;
void Start ()
{
MinRotation = transform.rotation.z - 80f;
MaxRotation = transform.rotation.z + 80f;
DoorRotation = transform.rotation;
}
public void RotatePositive ()
{
print ("Doorscript_RotatePositive");
DoorRotation = transform.rotation;
DoorRotation.z+=RotateAmount;
DoorRotation.z = Mathf.Clamp(DoorRotation.z, MinRotation, MaxRotation);
transform.rotation = DoorRotation;
}
public void RotateNegative ()
{
print ("Doorscript_RotateNegative");
DoorRotation = transform.rotation;
DoorRotation.z-=RotateAmount;
DoorRotation.z = Mathf.Clamp(DoorRotation.z, MinRotation, MaxRotation);
transform.rotation = DoorRotation;
}
}
I'm trying to rotate the door, and clamp it by 90 degrees (Both set to 80 for debugging) both ways, so the door can only swing 180 degrees. Problem is, upon rotating... The door flips on its side? Is this something with .Blend fbx?
Answer by Eric5h5 · Sep 02, 2014 at 12:13 AM
You can't (or rather shouldn't) directly alter quaternion components. Quaternions are 4D structs that don't use degrees, so attempting to alter the z component does nothing useful. Use Transform.Rotate instead.
Oh thank you so much! It seems like when I program I have the right idea but I use the wrong method, one time I was trying to program something with material opacity and I thought it was 0 to 255 when it was actually 0.0 to 1.0!
Wait how would I go about clamping it in C#? You cannot directly access transform in C#, you would have to store it in a variable.
Answer by Mikeywalsh · Sep 02, 2014 at 12:42 PM
Change DoorRotation to be Vector3 and not Quaternion and this should work.
public void RotateNegative ()
{
print ("Doorscript_RotateNegative");
DoorRotation = transform.rotation.eulerAngles;
DoorRotation.z -= RotateAmount;
DoorRotation.z = Mathf.Clamp(DoorRotation.z, MinRotation, MaxRotation);
transform.rotation = Quaternion.Euler(DoorRotation);
}
This helps but does not fix clamping, so I moved DoorRotation = trasform.rotation.eulerAngles;
to void Start()
and it worked. Thanks for the help guys!
Your answer
Follow this Question
Related Questions
How to find a rotation of a child object 0 Answers
Quaternion rotation infinite? 1 Answer
Quaternion + many collision meshes = intense lag? 0 Answers
90 Degree stopping rotation on y-axis issue 0 Answers
Rotate object smoothly problem 3 Answers