June 23, 2018
Press Releases
June 23, 2018
Games Press
• Editor-In-Chief:
Kris Graft
• Editor:
Alex Wawro
• Contributors:
Chris Kerr
Alissa McAloon
Emma Kidwell
Bryant Francis
Katherine Cross
Libby Kruse

If you enjoy reading this site, you might also want to check out these UBM Tech sites:

# Animation in 2D Unity Games: In-Depth Starter Guide

by Alex Rose on 09/05/13 10:12:00 am

The following blog post, unless otherwise noted, was written by a member of Gamasutra’s community.
The thoughts and opinions expressed are those of the writer and not Gamasutra or its parent company.

# Animation in 2D Unity Games: In-Depth Starter Guide

So, Unity recently announced extra 2D game support, with the addition of Box 2D physics and a sprite manager.

But thereâ€™s a few tricks you still need to keep in mind. Changing the images frame by frame is just the tip of the iceberg for animation; to really make your game run beautifully, you have to understand how to use translation and rotation to your advantage.

## Frame Changing

So, you have your textures ready for animation. You may be using the publicly available SpriteManager script, the paid version, or Unityâ€™s own new version, in which case frame advances should be pretty second nature. Letâ€™s say youâ€™re using 2D planes and textures for now though. Itâ€™s an inefficient method, but if youâ€™re doing a game jam for instance, you might want to throw together something thatâ€™s functional and good looking, but not necessarily efficient. Itâ€™s also a fairly comprehensive method that covers all steps, some of which are cut out by sprite managers.

First of all, youâ€™re going to want a public Texture[] array, so you can drag your textures into the object from Unityâ€™s editor and an integer currentTexture initialised to 0 in Start(). Next you want a NextTexture() function that works like this:

 Â `NextTexture(){` `currentTexture++;` `if``(currentTexture>=textureArray.Length) currentTexture=0;` `AnimatedPlane.renderer.material.mainTexture = textureArray[currentTexture];}`

This will change the planeâ€™s texture to the next frame in the animation.

There are two easy ways to call this function: Coroutine recursion and fixed intervals.

Using fixed intervals is the quickest (but less precise) method. Youâ€™re going to need an int counter, initialised to 0 in your Start() function, and a FixedUpdate() function, which updates every Time.deltaTime (you can vary this yourself in Unityâ€™s Time Manager).

Inside FixedUpdate(), place your conditional (e.g. if(walking)), and inside it increment your counter with counter++. Then set the following statement:

 Â `if``(counter>=animationDelay){` `counter=0;` `NextTexture();` `}`

Where animationDelay is an arbitrary value of your own choosing. This will advance the frames at a constant rate (depending on the rate you set in Unityâ€™s Time Manager.

The second method is to use recursion. The downside to this is that itâ€™s clumsier to deal with conditionals, but youâ€™ll get the exact time delay you want. This is especially useful if you want a certain frame to be of a longer or shorter length.Â Youâ€™ll need an IEnumerator TextureChanger() and to StartCoroutine(TextureChanger()) in Start().

 Â `IEnumerator TextureChanger(){` `yield ``return` `new` `WaitForSeconds(timeInterval);` `if``([conditions]) NextTexture();` `}`

Where timeInterval is a float of your choosing. With these functions, you can drag any number of textures onto your GameObject and itâ€™ll animate correctly, provided you give the right conditions.

Now letâ€™s move on to something more interesting.

## Smooth Movement to a Point

The following formula is the holy grail of animation:

$The holy grail of 2D animation in Unity$

where 0 < slidespeed < 1. I recommend 0.1f as a good slidespeed value.

This formula will allow you to animate your objects beautifully to a point. This is extremely
useful in sliding GUIs, character control, level spawning, camera following, colour fading/shiftingÂ etc.

Hereâ€™s an advanced version of it from myÂ upcoming game Rotation StationÂ that moves towards a lowerÂ point first and then back to a higherÂ point to make the little bob at the end. Every tile moves down according to that formula, although each one has a random delay, and a random initial rotation, which also uses this formula to rotate it into its desired orientation.

An example of using this for characterÂ controls is in my recent Ludum Dare entry Rude Bear Radio. In this case, the formula is applied to make fluent mouse controls.

So, letâ€™s look at how to apply it in the above example (a 2D GameObject following the mouse).

First of all, we need to know where the mouse is on the 2D area. In order to find that, we first place this code into the FixedUpdate() function of the sliding GameObject:

 Â `Vector3 MousePosition = Camera.main.ScreenToWorldPoint(``new` `Vector3(Input.mousePosition.x,Input.mousePosition.y, transform.position.z-Camera.main.transform.position.z));`

So, this uses the mouseâ€™s x and y position, and the distance from the camera to the sliding GameObject to determine the Mouseâ€™s 2d position in 3d coordinates. Now weâ€™re going to adapt the formula from the start of this section. So, remember,

$2D Step animation in Unity$

 Â `transform.position += ``new` `Vector3((MousePosition.x-transform.position.x),(MousePosition.y-transform.position.y),0)*slidespeed;`

And there you are â€“ done! Two lines of code. For something like a GUI, you would then write a statement saying:

if(Mathf.Abs(finalvalue-currentvalue)

Letâ€™s look at another example, which you can see in Rude Bear Radioâ€™s hard mode Mario stage.

The background animates from black to white slowly, using this formula:

 Â `background.renderer.material.color = (1-factor)*background.renderer.material.color+factor*desiredcolor;`

You can see here that it follows the basic form. Next = current+(final-current)*factor, just via shorthand. The factor starts low.Â The codeÂ checks whether the R valueÂ is within a certain range of the color, and if it is, it shifts up the factor so it fades quicker. Once the R value gets really close to 1, it sets the desired colour to black. You could also check for R, G and B, andÂ advance the colours in an array (similar to our NextTexture() function from before). You can see an example of this constantly in the background of my second LD entry Rude Bear Rising (which is a buggy mess, but a good example of this feature, and also uses this formula to focus the camera on the player once they move too far from the screen).

Okay, so this has all been easy so far, you just stick in a formula and itâ€™s done. The next (and possibly most important principle of all) requires a bit more thought than that.

## Trigonometry and You (Or: Why you shouldâ€™ve been paying attention in Maths)

Trigonometry is crucial to animation. Frames are all well and good, but they wonâ€™t make things look truly beautiful, and sometimes you can do without the frames at all.

e.g. The first time I entered Ludum Dare, my housemate hand drew the pictures for me. I had one still image for each character. The solution? Use puppets on sticks.

Now, the way to achieve motion like this is very simple. Sin for translation, cos for rotation.

To create animation like this, youâ€™re going to want the waves to stop and continue when you let go and input again, otherwise the motion will be extremely sporadic.

So you want an overarching variable (which I called walkbob), which adds Time.deltaTime onto it in FixedUpdate as long as the object is moving. Then you make your functions.

 Â `translation = maxHeight*Mathf.Sin(speed*walkbob);` `rotation =Â  maxRoll*Mathf.Cos(speed*walkbob/2);`

Then you simply set the position and rotation to these values (e.g. transform.position = new Vector3(transform.position.x,translation,transform.position.y)).

This will handle motion like that. However, a kind of animation that requires a bit more thought is what I like to call trig dancing. Itâ€™s useful forÂ making cute characters dance to the music. You can see it here in Rude Bear Radio.

So, hereâ€™s how it works. First of all, as soon as you intend to start moving your object, you want to take a float initialtime = Time.time. This is so that your object starts in the correct position and orientation and doesnâ€™t suddenly leap into action.

Next, weâ€™re going to think properly about trig functions and what they mean.

Weâ€™re using simple harmonic motion, and this follows the form:

$Sin formula for 2D animation in Unity.$

where y is the current value, A is the amplitude, f the frequency, t is the elapsed time andÂ phi is the phase. First of all, the amplitude is easy to determine. Thatâ€™s the maximum height or rotation we want our object to have.

Next is the elapsed time and phase. Weâ€™re going to handle both at once easily by replacing t by (Time.time-initialtime). This reduces Ï† to 0. So, finally, we just need our frequency. I would heavily recommend fitting the frequency of this to the frequency of your music (which is especially easy if you wrote it yourself).

If you donâ€™t already know the BPM of your music, go here and tap every beat until you know it. If you have rhythm itâ€™ll take no time. If you donâ€™t, no worries, weâ€™ll just take advantage of the central limit theorem. Just keep tapping for the whole duration of your song. The error on the average value will decrease with every tap.

So now you know it in beats per minute. Youâ€™ll need to divide this value by 60 to find out how many beats per second. Then you may want to divide it by 2 or 4 (or even more), if you only want to use motion on half a bar, or a full bar. This value is the frequency, and you can get pi from Mathf.PI. So now you just want to set the objectâ€™s position to that value. So, say youâ€™re only modifying the height:

 Â `transform.position = ``new` `Vector3(transform.position.x,maxheight*Mathf.Sin(2*Mathf.PI*frequency*(Time.``time``-initialtime)),transform.position.z);`

But this isnâ€™t good enough. First of all, we want the object to arrive on the beat, so it should start at its maximum amplitude. We want to use cos in this case. But more importantly, it should be leaping from side to side, so it shouldnâ€™t just slide up and down like a wave. It needs to use cos^2, so it abruptly stops at the 0 mark and becomes positive again. Therefore:

 Â `transform.position = ``new` `Vector3(transform.position.x,maxheight*Mathf.Pow(Mathf.Cos(2*Mathf.PI*frequency*(Time.``time``-initialtime)),2),transform.position.z)`

This takes care of the dancing height. Finally the rotation should use sin, such that the rotation and translation are out of phase. So:

 Â `transform.rotation = Quaternion.EulerAngles(0, maxRotation*Mathf.Cos(2*Mathf.PI*frequency*Mathf.Sin(Time.``time``-initialtime)), 0);`

Here there are two things to keep in mind: if youâ€™re using a plane and you want it to face the camera, those values arenâ€™t going to be 0 and 0, but pi/2 and â€“pi/2 respectively. But also of great importance is that Iâ€™ve used EulerAngles rather than Euler here. EulerAngles is deprecated in favour of Euler, because Euler uses degrees (which Unity usually handles) and EulerAngles uses radians. Weâ€™re doing proper maths â€“ weâ€™re working in radians, so use EulerAngles! Otherwise youâ€™re going to have to put in a conversion factor too.

Here you can see a similar kind of animation from the title screen of my upcoming game how you can change the scale instead of the position in the same way. Youâ€™ll have to use half the period and -cos^2 for this.

This brings us to the final category of animation Iâ€™ll discuss today:

## Texture Offsets

You can use everything youâ€™ve learnt so far to manipulate 2d texture offsets to make cool animated backgrounds. You can see this in my VVVVVV parody in Rude Bear Radio, and on its main screen. Iâ€™ll leave this one as an exercise. Grab a plane, stick a repeating texture on it, write up a FixedUpdate() function, and fiddle trigonometrically with these properties:

renderer.material.mainTextureOffset
renderer.material.color

This will cause the wall to slide around and change colour. Finally, if you want things to look really interesting, you can also play with renderer.material.mainTextureScale. It makes a really interesting looking effect, but it is rather distracting, and you donâ€™t want this to detract from your main gameplay.

Finally, you may want to look into lerp and slerp. These can make animation easier, but personally, I find it nicer to stick to the formula in the second section.

Enjoy!

Originally posted on my dev blog.
@Vorpal_Games

### Related Jobs

Galvanic Games, Inc — Seattle, Washington, United States
[06.22.18]

Multiplayer Game Engineer
Armature Studio — AUSTIN, Texas, United States
[06.22.18]

SENIOR GAMEPLAY PROGRAMMER
Square Enix Co., Ltd. — Tokyo, Japan
[06.21.18]

Experienced Game Developer
innogames — Hamburg, Germany
[06.21.18]

QA Engineer/ Software Engineer in Test