- Home /
Smoothly rotating a gameObject 90 degrees on a button press and being able to rotate it in the opposite direction off of the same button.
I'm having trouble rotating my magnification scope +90 degrees on a button press to move it to the seeing position through to my holographic sight. Everything I have tried through Update will just snap the scope to its position without smoothly moving. The Code For That:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MagnifierRotation : MonoBehaviour
{
public GameObject Magnifier;
Transform from;
Transform to;
float speed = 0.1f;
void Update()
{
if (Input.GetKeyDown(KeyCode.N))
{
transform.rotation = Quaternion.Lerp(from.rotation, to.rotation, Time.time * speed);
}
}
}
I've also tried using a Coroutine, but when I attempted to rotate the object off of its z-axis, it started rotating over all three axes instead of the z. The transform's rotation began at (-90, 0, 0), and after the coroutine rotation, of Vector3.forward, it ended up at a weird (-173. blahblahblah, 256.blahblahblah, 39.blahblahblah) instead of (0,0,0). The Code For That:
public class MagnifierRotation : MonoBehaviour
{
private bool magnifierSwitch;
IEnumerator RotateMe(Vector3 byAngles, float inTime)
{
var fromAngle = transform.rotation;
var toAngle = Quaternion.Euler(transform.eulerAngles + byAngles);
for (var t = 0f; t < 1; t += Time.deltaTime / inTime)
{
transform.rotation = Quaternion.Slerp(fromAngle, toAngle, t);
yield return null;
}
}
void Update()
{
if (magnifierSwitch && Input.GetKeyDown(KeyCode.M))
{
StartCoroutine(RotateMe(Vector3.right * -90, 0.8f));
magnifierSwitch = !magnifierSwitch;
}
else if (!magnifierSwitch && Input.GetKeyDown(KeyCode.M))
{
StartCoroutine(RotateMe(Vector3.right * 90, 0.8f));
magnifierSwitch = !magnifierSwitch;
}
}
}
I have also tried Quaternion.Euler's and the good old transform.Rotate, but both have the same effect as the Quaternion.Lerp that just snapped the object when in Update and under an if statement checking for an input. If there is any other way to make the object smoothly rotate on a button press in both directions after one rotation is over, please let me know before I just make a broken looking animation.