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.
Weâ€™ll start with the basics for now though:
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:
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:
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().
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.
The following formula is the holy grail of animation:
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:
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,
And there you are â€“ done! Two lines of code. For something like a GUI, you would then write a statement saying:
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:
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 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.
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.
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:
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:
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:
This takes care of the dancing height. Finally the rotation should use sin, such that the rotation and translation are out of phase. So:
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:
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:
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.