- Home /
How can I rotate an object by set amount over time
The effect I want is when I press the left and right arrow keys, the player character rotates by 90 degrees over a short time, so it isn't so snappy. How do I script the actual rotation code when the rotation values are switching between 180 and -180 so often?
Answer by zeysoft · Nov 27, 2009 at 08:26 AM
Other version of Murcho's example is:
// This should be set to degrees per second float rotationAmount = 90.0f;
void Update() { // Clamps automatically angles between 0 and 360 degrees. transform.Rotate (0, rotationAmount * Time.deltaTime, 0); }
Answer by Murcho · Nov 27, 2009 at 03:32 AM
Define a rotation speed, and then multiply that by Time.deltaTime in you update loop. If using Euler angles to perform the rotation, you can clamp between 0 and 360 very easily.
// This should be set to degrees per second float rotationAmount = 90.0f;
void Update() { Vector3 rot = transform.rotation.eulerAngles; rot.y = rot.y + rotationAmount * Time.deltaTime; if(rot.y > 360) rot.y -= 360; else if(rot.y < 360) rot.y += 360;
transform.eulerAngles = rot;
}
Answer by Bampf · Nov 27, 2009 at 03:30 AM
Instead of thinking in terms of absolute rotation, which indeed will switch signs on you, all you really need to do is add or subtract 90 degrees from whatever the current rotation is. Don't worry if you go past 180 or 360; the math should handle that case.
You also seem to be asking how to rotate it smoothly over time. You can do this by interpolating between the starting angle, whatever it is, and the final angle, which is 90 degrees more or less. See Mathf.Lerp for a function that will help you calculate what the angle is after a certain amount of time. (Also see the answer to this question, which is solving a problem of smooth movement rather than smooth rotation, but the idea is similar.)
Your answer
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
How to apply 2 gameobjects together one with a rotation and the other without? 1 Answer
How do I swap two objects without them colliding ? 1 Answer
Add Force to the right of the rigidbody, not right of the screen 1 Answer
Why does the rotation value differ? 1 Answer