- Home /
Rotate to a set degree then reverse and repeat
Hello, and thank you for your time.
I'm making my first project in Unity, a simple game where touching objects adds points to the players score.
I'd like the objects to have a pleasant back and forth swaying animation on the Z axis. Nodding to the right 30 degrees, then to the left 30 degrees, on and on.
Here's what I've got...
public class Rotator : MonoBehaviour
{
void Update ()
{
transform.Rotate(new Vector3(0,0,12)*Time.deltaTime);
}
}
This gives me a nice slow rotation. But I am clueless how to tell Unity to stop at +30 degrees, reverse to -30 degrees, rotate again to +30, stop and repeat, etc, etc.
I'd really appreciate any help. Maybe there is a thread like this that I was not able to find? I assume it will involve some kind of 'if than' function?
Thank you,
Answer by Dave-Carlile · Nov 09, 2013 at 09:27 PM
I just learned about Mathf.PingPong the other day. It's possible to do it manually, but PingPong
should work well for you.
Something like this? Not tested, but should point you in the right direction...
transform.Rotate(new Vector3(0, 0, Mathf.PingPong(Time.time, 60) - 30));
The PingPong
call should smoothly give you values that go back and forth between 0 and 60 over time. Subtracting 30 moves makes the range -30 to +30.