- Home /
Rotating An Object On Its Axis Once
I can't seem to find out how to do this just right. My basic idea is that there is a lever that, when the key "e" is pressed, will rotate to give it the effect that it is activated. This is a 2D game, so the lever is a plane. I have a custom pivot point at the middle-bottom of the plane.
How can I rotate the object JUST to the left one time when the "e" key is pressed? I have tried multiple different options, but they all cause the plane to go in strange directions. The only one that has worked so far is:
function Update () {
if (Input.GetKey ("e") {
transform.Rotate (0, 45, 0 * Time.deltaTime, Space.World);
}
}
This did rotate the object gradually in the right direction as the "e" key was held, but this isn't exactly the effect I'm going for. I want an automatic rotation, which will stop at a certain angle.
Any ideas? Help is greatly appreciated.
-myjean17
EDIT**
Well, I haven't exactly solved my problem. So if anyone still wants to answer this question please do. But I instead created an animation for the lever turning on and off, and tied them together and its actually functioning quite well.
try using a separate function that does the rotating for 90 deg. and call that function with your e key
I Think Ive figured it out... mostly. I used a boolean to check if the function had been run, so it would only perform the rotation once. Now, however, i would like to rotate it gradually and not just have it appear in the new location.
Answer by robert_mathew · Dec 12, 2011 at 04:11 PM
float rotationleft = 360; float rotationspeed = 10;
void Update() { float rotation = rotationspeed * Time.deltaTime;
{
rotationleft-=rotation;
}
else
{
rotation = rotationleft;
rotationleft = 0;
}
transform.Rotate(0,0,rotation);
}
How about writing an actual answer? Also the OP uses UnityScript (JS) and not C#. Furthermore Your code seems missing an if statement because it doesn't make any sense this way.
ps. for the future: format your code in a way it's readable.
Is there an if missing in there? It would help if you could please explain what you just posted.
Answer by suruz@kento · Dec 13, 2011 at 02:58 AM
Use Quaternion.Euler() to control rotation.
private var startRotY: float = 0; private var endRotY: float = 0; var currentRotY: float;
function Update () {
if (Input.GetKey ("e") )
{
currentRotY = 0;
startRotY = 0;
endRotY = 45;
transform.rotation = Quaternion.Euler(0,0 ,0);
}
currentRotY++;
currentRotY = Mathf.Clamp(currentRotY,startRotY,endRotY);
transform.rotation = Quaternion.Euler(0,currentRotY ,0);
}
Answer by SZ_95 · Sep 08, 2015 at 09:19 AM
This should work correctly. It turns an object one time (and only one time) 90 degrees on the Z axis.
using UnityEngine;
usingSystem.Collections;
public class RotateHalt : MonoBehaviour
{
bool turn;
if (Input.GetKeyDown(KeyCode.Q)) {
turn = true;
if(turn == true)
{
Vector3 rotation = new Vector3(0, 0, 90);
transform.Rotate (rotation);
}
turn = false;
}
}