Search Unity

Rotation based on Time.time

Discussion in 'Scripting' started by Cramonky, Jan 8, 2019.

  1. Cramonky

    Cramonky

    Joined:
    Apr 1, 2013
    Posts:
    186
    Hey all,

    I have a simple script which just makes an object spin:

    Spin Speed is the speed in degrees per second for each axis. Local is whether or not the rotation is in Local or World space. Starting Rotation is just the initial rotation the calculations are based off of.

    The tricky thing is that, rather than using something like Transform.Rotate to do the rotation, the rotation needs to be a function of time, so for example Time.time. I have code working for world space:
    Code (CSharp):
    1. private Quaternion getRotation(float time)
    2. {
    3.     Vector3 angles = Vector3.zero;
    4.     angles = StartingRotation + SpinSpeed * time
    5.     return Quaternion.Euler(angles);
    6. }
    You can pass any time you want into this function and it will return what the rotation should be at that time. I'm just not sure of how to implement rotation using local space.

    Thanks!

    Edit: Just realized the above code doesn't actually work :eek: I'll leave it there anyways as an example of what I'm trying to do
     
    Last edited: Jan 8, 2019
  2. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,196
    Did you already try simply using the local versions of transform.rotation/transform.eulerAngles? (transform.localRotation/transform.localEulerAngles)
     
  3. WallaceT_MFM

    WallaceT_MFM

    Joined:
    Sep 25, 2017
    Posts:
    394
    Do you mean like this?
    Code (csharp):
    1. private Quaternion getRotation(float time)
    2. {
    3.    return Quaternion.Euler(SpinSpeed * time, + StartingRotation);
    4. }
    5.  
    6. private void Update()
    7. {
    8.    if(local)
    9.       transform.localRotation = getRotation(Time.time);
    10.    else
    11.       transform.rotation = getRotation(Time.time);
    12. }
     
  4. Cramonky

    Cramonky

    Joined:
    Apr 1, 2013
    Posts:
    186
    No, that's not really what I'm looking for. I need to do something like how Transform.Rotate allows you to specify a relativeTo parameter of either Space.World or Space.Self when doing a rotation.

    Space.World behaves like this when i have a SpinSpeed of 180 on the y axis:
    https://i.gyazo.com/d7f41b6a88425b5d8b8237cd7ac40878.gif

    Space.Local behaves like this when i have a SpinSpeed of 180 on the y axis:
    https://i.gyazo.com/d453b3dd239c9f77b86ce372c499d068.gif

    Of course Transform.Rotate takes an amount to rotate by, where as I need to calculate the rotation when given just a time value.