0
\$\begingroup\$

I have a simple script to make an object spin: Script in inspector

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

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – DMGregory Jan 10 at 1:43
  • \$\begingroup\$ I added some gifs showing the kind of behaviour I am looking for. I also moved my edit to an answer. \$\endgroup\$ – Crazymonkay Jan 10 at 2:11
  • \$\begingroup\$ If you keep the file size of your gifs low, you can embed them directly inside the question. \$\endgroup\$ – DMGregory Jan 10 at 2:12
0
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.