Hi guys,
I have this game object that I am trying to rotate 90 degrees clockwise or anticlockwise according to user input.
Every time the user presses a key the object should slowly rotate 90 degrees and wait there . if the user presses the same key again it will rotate 90 degrees farther in the same direction, otherwise if the player presses the negative key for , the object rotates 90 degrees in the opposite direction… and so on.
So far i have this script. but the rotation is faulty, since every-time the player does an input, the rotation values get reset to (0,0,0)
buttonz.x is -1 on keypress ‘q’ and 1 on keypress ‘e’.
function Start () {
}
function Update () {
if (buttonz.x==-1) {
MyRotate();
buttonz.x=0;
}
if (buttonz.x==1) {
MyRotato();
buttonz.x=0;
}
}
function MyRotate() {
for(var i = 0; i<90; i+=2) {
//print ("Entered for. Value is " + transform.eulerAngles.z);
yield;
transform.eulerAngles = Vector3(0, 0, i);
}
}
function MyRotato() {
for(var i = 0; i>-90; i-=2) {
//print ("Entered for. Value is " + transform.eulerAngles.z);
yield;
transform.eulerAngles = Vector3(0, 0, i);
}
}
Please help…
Thank You
1 Answer
1
You are directly assigning to ‘eulerAngles’ so that is giving your object an absolute rotation. So you code rotates the angle between 0 and 90 or 0 and -90. As a quick fix, you can change the code to use Transform.Rotate():
#pragma strict
function Update () {
if (Input.GetKeyDown(KeyCode.A)) {
MyRotate();
}
if (Input.GetKeyDown(KeyCode.S)) {
MyRotato();
}
}
function MyRotate() {
for(var i = 0; i<90; i+=2) {
//print ("Entered for. Value is " + transform.eulerAngles.z);
yield;
transform.Rotate(0,0,2);
}
}
function MyRotato() {
for(var i = 0; i>-90; i-=2) {
//print ("Entered for. Value is " + transform.eulerAngles.z);
yield;
transform.Rotate(0, 0, -2);
}
}
There is one problem with this code…it is not frame rate independent. That is, it rotates two degrees for each frame, so it will be twice as fast when Unity is run at 60 fps on the desktop compared to 30 fps it might run on a smart phone.
So here is a bit different take on it that is frame rate independent:
#pragma strict
public var speed = 55.0;
private var rotation = 0.0;
private var qTo = Quaternion.identity;
function Update () {
if (Input.GetKeyDown(KeyCode.A)) {
rotation += 90.0;
qTo = Quaternion.Euler(0.0, 0.0, rotation);
}
if (Input.GetKeyDown(KeyCode.S)) {
rotation -= 90;
qTo = Quaternion.Euler(0.0, 0.0, rotation);
}
transform.rotation = Quaternion.RotateTowards(transform.rotation, qTo, speed * Time.deltaTime);
}
I'm trying to get rotations as well. I can't really give you an answer but all my research is pointing me towards quaternion.Slerp Looking up quaternion and slerp functions may point you in the right direction :) Wish I could help more.
– Jabes22