I would like to rotate an object back and forth between 90,-90 on the Y axis. The problem is I can set the object in the editor at -90, but when I run the project -90 suddenly becomes 270. Anyway here is the code that I'm using:
void Update()
{
if (transform.eulerAngles.y >= 270)
{
transform.Rotate(Vector3.up * speed * Time.deltaTime);
}
else if (transform.eulerAngles.y <= 90)
{
transform.Rotate(Vector3.up * -speed * Time.deltaTime);
}
}
It always gets stuck in the middle around 360 degrees. Help?
First of all you should always ensure that the angle stays between
0
and359
, meaning that0 == 360
:After that you can check if it's between your minimum and maximum value :
Another issue with your code is that it will stuck somewhere between
350
and10
degrees. To explain this in more details let's assume your speed is10
,Time.deltaTime
will be1
as well and starting angle is300
, now frame steps :... and this will go forever.
To deal with this you have to make some condition based on user input or if you want your camera to "bounce" between these two angle then you can try something like this :
Just like moving GameObject back and forth, you can rotate GameObject back and forth with
Mathf.PingPong
. That's what it is used for. It will return value between 0 and 1. You can pass that value toVector3.Lerp
and generate the eulerAngle required to perform the rotation.This can also be done with a coroutine but
Mathf.PingPong
should be used if you don't need to know when you have reached the destination. Coroutine should be used if you want to know when you reach the rotation destination.EDIT:
With the coroutine method that you can use to determine the end of each rotation.