dipam
1
I am working in a demo game project in which, there is a tower that shot bullets and can rotate from -30 to +30 then +30 to -30 and continue this rotation forever. I am having problem with roatation. I am using Quaternion.Slerp to rotate it from -30 to 30 (rotating fine). But i am unable to make the reverse rotation from +30 to -30. Please help me how to do that reverse rotation. I am new to Unity. Thank you!
//Here is my code
using UnityEngine;
using System.Collections;
public class RotateTo : MonoBehaviour
{
private Quaternion rotationFrom;
private Quaternion rotationTo;
void Start () {
rotationFrom = Quaternion.Euler(0.0f, -30, 0.0f);
rotationTo = Quaternion.Euler(0.0f, 30, 0.0f);
}
// Update is called once per frame
void Update ()
{
transform.rotation = Quaternion.Slerp(rotationFrom, rotationTo, 0.5f * Time.time);
}
}
You’re close, you just need to flip flop the numbers when you reach your goal:
private Quaternion rotationFrom;
private Quaternion rotationTo;
float ellapsedTime = 0f;
void Start () {
rotationFrom = Quaternion.Euler(0.0f, -30, 0.0f);
rotationTo = Quaternion.Euler(0.0f, 30, 0.0f);
}
// Update is called once per frame
void Update ()
{
ellapsedTime += Time.deltaTime;
transform.rotation = Quaternion.Slerp(rotationFrom, rotationTo, 0.5f * ellapsedTime);
//if we get within a 10th of a degree...
if (Quaternion.Angle (transform.rotation, rotationTo) < .1f)
{
//Start our time over
ellapsedTime = 0f;
//Flip flop our values
Quaternion temp = rotationTo;
rotationTo = rotationFrom;
rotationFrom = temp;
}
}