- Home /
Question by
CrazyKane · Jan 12, 2014 at 05:22 PM ·
rotate objectvar type
Not Rotating Properly
var upKey: KeyCode;
var downKey: KeyCode;
var leftKey: KeyCode;
var rightKey: KeyCode;
var gO: GameObject;
function Update () {
if(Input.GetKeyDown(upKey)){
gO.transform.rotation.z = 270;
}
else if(Input.GetKeyDown(downKey)){
gO.transform.rotation.z = 90;
}
else if(Input.GetKeyDown(leftKey)){
gO.transform.rotation.z = 0;
}
else if(Input.GetKeyDown(rightKey)){
gO.transform.rotation.z = 180;
}
}
When ever i go down or up it sticks at 180 degrees on the z axis. Can someone help me?
Comment
Best Answer
Answer by sanmn19 · Jan 12, 2014 at 06:10 PM
You are trying to modify the quaternions which I think is not what you intend. Quaternions have 4 components w,x,y,z. What you want to modify is the x, y and z rotation of the object. So, here is the script that should suit your needs:
var upKey: KeyCode;
var downKey: KeyCode;
var leftKey: KeyCode;
var rightKey: KeyCode;
var gO: GameObject;
function Update () {
if(Input.GetKeyDown(upKey)){
gO.transform.rotation.eulerAngles.z = 270;
}
else if(Input.GetKeyDown(downKey)){
gO.transform.rotation.eulerAngles.z = 90;
}
else if(Input.GetKeyDown(leftKey)){
gO.transform.rotation.eulerAngles.z = 0;
}
else if(Input.GetKeyDown(rightKey)){
gO.transform.rotation.eulerAngles.z = 180;
}
}
Theres only 1 problem with it, when i go down it doesn't change. I can't figure out why.
Answer by KellyThomas · Jan 12, 2014 at 05:27 PM
Tranform.rotation
is of type Quaternion. It's w,x,y,z properties are not the angles you are expecting.
If you want to apply angles use the following pattern:
var angles: Vector3 = tranform.rotation.eulerAngles;
angle.z = 90.0f;
tranform.rotation = Quaternion.Euler(angles);
Your answer
![](https://koobas.hobune.stream/wayback/20220613130210im_/https://answers.unity.com/themes/thub/images/avi.jpg)