- Home /
How to rotate an object along the Y axis to the right, and then to the left?
How to rotate an object along the Y axis to the right, and then to the left by a certain number of degrees. The object moves and rotates randomly, so the starting angle can be any.
Answer by Tario · Apr 28, 2020 at 05:34 PM
Sine wave.
Mathf.Sin(x); outputs a value that will go from zero, up to one, then down to -1 and back to zero at a constant, smooth rate as you increase the value of x. Use that, along with the Quaternion.Euler(); method.
Want more than 1 degrees change? No problem! Multiply the output of Mathf.Sin(x); by the maximum number of degrees you want. At 1, you'll have all your degrees, at 0, you'll have none and at -1, you'll be looking the other direction.
Alternatively, look into Mathf.Pingpong();
Answer by LuigiDreemurr · Apr 28, 2020 at 05:58 PM
void Update
{
float y = 5; //easy variable for y
this.gameObject.transform.localEulerAngles = new Vector3(0, y, 0);
}
This changes the local y angle to 5 degrees, you can also just use EulerAngles for worldspace angles instead of local. As for wanting to change it I assume you want it over time otherwise its gonna twitch out. I recommend using an IEnumerator for that if its always running else Update will work fine, just be sure to set a speed and multiply it by DeltaTime. Deltatime ensures a smooth transition over time, otherwise your code runs once a frame and any transforms will be done way to fast.
private float y = 0; //we need to store the variable outside so to not have it reset every time update is called.
public float rotationSpeed = 5; //This is a public variable that we can change for preferred rotation speed.
public float desiredAngle = 30;
void Update
{
//This will increase the angle over time
y += rotationSpeed * Time.deltaTime;
//This changes the local Euler angle(Standard degrees) of y while keeping x and z at 0
this.gameObject.transform.localEulerAngles = new Vector3(0, y, 0);
If (y > desiredAngle || y < 1) //I do this to avoid getting gimble locked
rotationSpeed = -rotationSpeed ; //and with a simple negitave switch we change the direction of the rotation.
}
Hope this answers all of your current questions! Happy coding!
If rotation.y is not zero, when the code starts to execute, the object takes the coordinate rotation.Y at 0. How to make the object start rotation from the current position along the y axis?
Your answer
