# Unity - Calculating a rotation based on game time

I have a simple script to make an object spin: Spin Speed is the speed to rotate the object on each axis (preferably in degrees per second). Local is whether the rotation should be done based on world axes or object axes. Starting Rotation is the initial rotation of the object.

Normally I would use Transform.Rotate to do the rotation, but in this case I have to make the rotation a function of time, so you can pass in any time value and it will return what the rotation should be at that time.

Here is an example (this doesn't work properly for either world or object axis rotation):

private Quaternion getRotation(float time)
{
return Quaternion.Euler(InitialRotation + SpinSpeed * time);
}


I just need some help figuring out the math behind calculating rotations for both world and object axes. I think that matrices can be used but I honestly don't remember anything about how to use them.

Here's an example of using world axes with a SpinSpeed of 180 on the y axis and an initial rotation of 45 on the x axis: https://i.gyazo.com/d7f41b6a88425b5d8b8237cd7ac40878.gif

An example of using local axes with the same parameters as above: https://i.gyazo.com/d453b3dd239c9f77b86ce372c499d068.gif

• Post your solution as an answer, not as an edit to the question. It would also be helpful to describe what your desired behaviour looks like so we can use that to validate candidate answers. – DMGregory Jan 10 '19 at 1:43
• I added some gifs showing the kind of behaviour I am looking for. I also moved my edit to an answer. – Crazymonkay Jan 10 '19 at 2:11
• If you keep the file size of your gifs low, you can embed them directly inside the question. – DMGregory Jan 10 '19 at 2:12

This is a bit of a hack solution I came up with:

//Save rotation at the start of the frame
Quaternion rot = transform.rotation;
//Set rotation to InitialRotation
transform.rotation = Quaternion.Euler(InitialRotation);
//Perform rotation
transform.Rotate(SpinSpeed * time, Local ? Space.Self : Space.World);
//Save the calculated rotation
Quaternion targetRot = transform.rotation;
//Reset rotation to what it was at the start of the frame
transform.rotation = rot;
//Set rigidbody rotation to target
rigidbody.MoveRotation(targetRot);


I won't close this just yet in case someone can answer with a less-hacky way of doing this. Otherwise I will close this question if I don't get any answers.