- Home /
How to turn your object left and right
I want my cube to turn left and right while moving my cube ahead my code for turning left in every state of cube , code is as follows
using UnityEngine; using System.Collections;
void Update () {
transform.position += transform.forward * speed * Time.deltaTime;
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
if (transform.rotation.y == 0)
{
transform.rotation = Quaternion.Euler(0, -90 , 0);
}
else if (transform.rotation.y == -90)
{
transform.rotation = Quaternion.Euler(0, -180 , 0);
}
else if (transform.rotation.y == -180)
{
transform.rotation = Quaternion.Euler(0, -270 , 0);
}
transform.Rotate(Vector3.left * Time.deltaTime * speed );
}
} it works till for the first left turn then when again i press left arrow key nothing happens
Answer by robertbu · Jul 27, 2014 at 02:44 PM
'transform.rotation' is a Quaternion...an non-intuitive 4D construct with values between -1 and 1. There is a transform.eulerAngles that measures rotation in degrees, but you would not want to do a direct comparison between floating point values like you do here. Given floating point imprecision, the comparison will fail. If you want to allow complete rotation (i.e. rotation does not stop at -270, you can replace all of your LeftArrow code with:
if (Input.GetKeyDown(KeyCode.LeftArrow)) {
transform.Rotate(0.0f, -90.0f, 0.0f);
}