x


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?

more ▼

asked Nov 27 '09 at 01:11 AM

Joe gravatar image

Joe
27 1 1 1

(comments are locked)
10|3000 characters needed characters left

3 answers: sort voted first

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);
}
more ▼

answered Nov 27 '09 at 08:26 AM

zeysoft gravatar image

zeysoft
62 2

(comments are locked)
10|3000 characters needed characters left

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.)

more ▼

answered Nov 27 '09 at 03:30 AM

Bampf gravatar image

Bampf
5k 8 19 49

(comments are locked)
10|3000 characters needed characters left

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;
}
more ▼

answered Nov 27 '09 at 03:32 AM

Murcho gravatar image

Murcho
2.7k 12 23 53

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x2156

asked: Nov 27 '09 at 01:11 AM

Seen: 5857 times

Last Updated: Nov 27 '09 at 01:11 AM