I have a cube, and I want to rotate it on a GetButtonDown event, but I only want it to rotate 90 degrees, and I don’t want it to be instantaneous (I’d like a short animation so it appears to rotate). I wrote this code, and it works! But it rotates by 90 degrees all at once on the GetButtonDown. Basically I’d like the GetButtonDown to start a short animation in which the cube rotates 90 degrees over - say 2 seconds.
Here’s the code I wrote:
using UnityEngine;
using System.Collections;
public class Control : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetButtonDown("RotateRight")) {
transform.Rotate(0, 90, 0);
}
if(Input.GetButtonDown("RotateLeft")) {
transform.Rotate(0, -90, 0);
}
}
}
I’ve looked into quaternions and slerps and I feel like the answer to my problem has something to do with those, but I don’t really understand how they work or how to utilize them yet.
An example of Lerp I just threw together, let me know if it helps (or even works), if it doesn’t I hope you get the general idea from it.
This makes use of the GetKey function to get input, much cleaner. Alpha1 is number 1 on your keyboard.
public class EXAMPLE : MonoBehaviour
{
bool cooldownActivated;
float spinningTime;
float timeStarted;
Quaternion rotateB;
Quaternion rotateA;
int count = 1;
void RunCooldownTimer()
{
float timeSinceStarted = Time.time - timeStarted;
float percentageComplete = timeSinceStarted / spinningTime;
transform.rotation = Quaternion.Lerp(rotateA, rotateB, percentageComplete);
if (percentageComplete >= 1)
{
cooldownActivated = false;
}
}
public void Activate()
{
spinningTime = 1;
cooldownActivated = true;
timeStarted = Time.time;
Transform thisTransform = gameObject.transform;
rotateA.eulerAngles = this.transform.rotation.eulerAngles;
rotateB.eulerAngles = rotateA * new Vector3(0, 0, 90 * count);
count++;
if (count == 5)
{
count = 1;
}
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.Alpha1) && cooldownActivated == false)
{
Activate();
cooldownActivated = true;
}
if (cooldownActivated)
{
RunCooldownTimer();
}
}
}
This took me a while, damn rotations! Hope you’re happy with it. This should be 100% what you’re looking for now. If you find it satisfactory don’t forget to mark as answered.