Wednesday, February 26, 2014

Continually rotate an object in Unity

In games it’s a very common task to rotate/spin an object continually, such as a coin, treasure box, health pack, weapons, etc. In Unity this is extremely simple. As with anything, there are multiple ways of doing it ex code or a particle system, but if we wan’t a quick script to do it, simply assign this script to your GameObject. Again, there are better ways. The quickest way may even be to just create a new animation, set a keyframe at 0 seconds, move to 1 second and rotate the object to 360 degrees and a new keyframe will be logged. From a performance standpoint, thats typically the best _but_ this script below can by dynamically applied to any object.
    private int _rotationSpeed = 90; //degrees per second = 4 seconds for a revolution
    void Update()
    {
        //Since deltaTime is the elapsed time since the last frame, 
        //let’s assume its one second. 1 * 90 = 90 degrees per second. 
        //Simple, right? Rotate’s parameters is (x,y,z, coordinate system)
        transform.Rotate(0, _rotationSpeed * Time.deltaTime, 0, Space.World);
    }
Voila - A spinning object!

There is however a basic optimization we can do here. Even though it seems that this is pretty simple, we can cache our transform. This prevents having to cross over from the 'managed' type of code that c#/mono/.net provides across boundaries into the native code from the c++ based engine that Unity wrote. This type of transition is slow so we can optimize it a little bit as follows by getting a reference to it upon start which is then stored in our c# code. We can then access it without having to do an extra hop into the native c++ code that the Unity engine runs on.
    private int _rotationSpeed = 90; //degrees per second = 4 seconds for a revolution
    private Transform _transform;
    void Start()
    {
     //cache the transform in our managed code side
      _transform = transform;
    }
    void Update()
    {
        //Since deltaTime is the elapsed time since the last frame, 
        //let’s assume its one second. 1 * 90 = 90 degrees per second. 
        //Simple, right? Rotate’s parameters is (x,y,z, coordinate system)
        _transform.Rotate(0, _rotationSpeed * Time.deltaTime, 0, Space.World);
    }
treasure spin

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete