Unity3d Beginner's 2D animation system

Source: Internet
Author: User
Tags add time cos sin

Alex Rose

Unity recently announced the introduction of additional 2D game support, adding box 2D physics and an Elf manager.

But there are some tricks to keep in mind. Changing the image frame by frames is just the tip of an animated iceberg, and you'll have to use features such as transformations and rotations to make your game work well.

Now let's start with the basic techniques.

Change Frame

If you're ready to animate textures, you might be using a paid version of the Spritemanager script, or a new version of unity. Let's say you're using 2D bit faces and textures. This is a inefficient approach, but if you're making a game jam project, you might want to cram in something that works and looks good but doesn't necessarily work. This is also a comprehensive approach that covers all the steps, which may be removed if you are in the wizard manager.

First, you'll need a public texture[] array, so you can drag textures into objects in the Unity Editor, and an integer currenttexturep initialized to 0 in start (). Next you need a nexttexture () function that runs like this:

Nexttexture () {
currenttexture++;
if (currenttexture>=texturearray.length) currenttexture=0;
AnimatedPlane.renderer.material.mainTexture = Texturearray[currenttexture];}

There are two easy ways to call this function: the recursive and fixed interval of the cooperative program.

Using a fixed interval is the quickest method (but less accurate). You need an integer counter, initialized to 0 in your start () function, and a fixedupdate () function (game state Note: Each time it is updated, you can adjust it yourself in Unity Time manager).

Place your conditional sentence (for example, if (walking)) in Fixedupdate () and add your timer to it with conter++, and then set the following declaration:

if (Counter>=animationdelay) {
counter=0;
Nexttexture ();
}

The animationdelay here can be any value you choose. This pushes the frame at a sustained speed (depending on the speed you set in the Unity Time manager).

The second method is to use recursion. But the disadvantage of this approach is that it is not easy to deal with conditional sentences, but you can still get the exact delay you need. This method is especially useful if you want to lengthen or shorten a particular frame. You need a IEnumerator Texturechanger () and to Startcoroutine (Texturechanger ()) in Start ().

IEnumerator Texturechanger () {
Yield return new waitforseconds (timeinterval);
if ([conditions]) nexttexture ();
}

Here TimeInterval is also your own choice of any value. With these functions, you can drag any number of textures to gameobject so that if you provide the correct conditions, it will run the animation correctly.

Now let's do some more interesting things.

Smooth move to a point

The following formula is a recipe for creating unity 2D animations:

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

This formula allows you to move the object perfectly to a point. This is especially useful in operations such as sliding GUI, character control, level generation, camera follow, fade/shift, etc.

Descension (from Gamasutra)

This is a high-level version of my upcoming new game, Rotation station, which moves from a lower point to a higher point and then to a small bubble. Each map moves down according to the company, but each map has a random delay, a random initialization rotation (also using this formula to rotate to the desired direction).

Examples of role control can be found in my recently launched Rude Bear Radio, which is used to create a smooth mouse control method.

Bearo-wing (from Gamasutra)

So, let's look at how to apply it to the above example.

First, we need to know that the mouse is in the 2D area. To find it, we will first place this code in 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));

This uses the X and y axes of the mouse, as well as the distance from the camera to the sliding gameobject to determine the 2D position and 3D coordinates of the mouse. Now we need to adjust the formula from the beginning of this session. So, remember the 2D steps in unity.

Transform.position + = new Vector3 (mouseposition.x-transform.position.x),
(MOUSEPOSITION.Y-TRANSFORM.POSITION.Y), 0) *slidespeed;

You just need these two lines of code to get it done! As for things like GUI, you can write a statement later:

if (Mathf.abs (Finalvalue-currentvalue)

Let's look at another example, "Rude Bear Radio" in the difficult mode of Mario steps.

Super-bario-bros (from Gamasutra)

The background uses the following formula from black to white:

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

You can see that it follows the basic form, shorthand is next = current+ (final-current) *factor. The code checks if the R value is in a certain color range, and if it does, it changes the factor to make it fade more quickly. If the R value is very close to 1, it sets its desired color to black. You can also check R, G, and B, and push the color in one array. You can see this example in the background of my second case project "Rude Bear Rising".

For now, these are very simple, you can copy the formula to do. The next step is to consider more factors.

The importance of trigonometry and mathematics

Triangulation is very important for animation production. Even with good frames, it's not always possible to make them look beautiful, and sometimes you don't need frames to do things at all.

For example, when I first entered Ludum Dare Studio, my roommate drew a few pictures for me. I still remember each of these roles, and how? Act like a puppet by tying a character to a stick.

Rudebear (from Gamasutra)

This movement is very simple, using sine (sin) when converting, and cosine (COS) when rotating.

To create this animation, you want the ripple to stop and continue when you let go and enter, or the action will be extremely scattered.

So you need a primary variable (what I call a walkbob), and as long as the object is still moving, it will add time.deltatime to the fixedupdate. After that, make your function:

Translation = Maxheight*mathf.sin (Speed*walkbob);
rotation = Maxroll*mathf.cos (SPEED*WALKBOB/2);

The position and rotation are then set to these values (for example, transform.position = new Vector3 (TRANSFORM.POSITION.X,TRANSLATION,TRANSFORM.POSITION.Y)).

This can handle something like that, but there is another kind of animation that needs to be considered, and this is what I call a triangle dance, which is used to make cute characters dance with the music, for example:

Rude-bear-radio (from Gamasutra)

First, when you want to move the game object, choose a floating initialtime = Time.time so that your object starts in the correct position and direction and does not suddenly jump into the action.

Next, we will think about the concept of trigonometric functions.

We use simple harmonic motion in the following form:

Y refers to the current value, a is the amplitude, f is the frequency, T is the run time, and Phi is the stage. First, we can easily determine the amplitude. It is the maximum height or rotation that we want the object to have.

The next is the run time and stage. We will use (Time.time-initialtime) easy to replace T and one-off to do both. This will reduce φ to 0, so in the end we just need to get the frequency. I highly recommend making this frequency consistent with your music frequency (it's easy to do this if you're composing yourself).

If you don't yet know the BPM of your music, then try to find the rhythm until you understand it. If you already have a sense of rhythm, this is a good run. If you don't, don't worry, we'll use the central limit theorem. Keep touching your entire song, and each less touch will reduce the errors in the average.

Now you know how it beats every minute. You will divide this value by 60来 to find how many beats per second. If you only want to use a single action in a half bar or a full bar, you can divide it by 2 or 4 values. This is the frequency, and you can get pi from Mathf.pi. So now you're going to set the object's position to that number. At this point you are just adjusting the height:

Transform.position = new Vector3 (transform.position.x,maxheight*
Mathf.sin (2*mathf.pi*frequency* (Time.time-initialtime)), transform.position.z);

But that's not good enough. First, we want the object to be in tune so that it starts at its maximum amplitude. We're going to use cosine at this point. But more importantly, let it jump from one end to the other so that it does not slide up and down like a ripple. Then use cos^2 so that it stops abruptly at the 0 mark and again moves toward positive numbers. So:

Transform.position = new Vector3 (Transform.position.x,maxheight*mathf.pow (Mathf.cos (
2*mathf.pi*frequency* (Time.time-initialtime)), 2), transform.position.z)

Pay attention to the height of the dance here. The final rotation is to use sine so that its rotation and transformation are heterogeneous. So:

transform.rotation = quaternion.eulerangles (0, maxrotation*
Mathf.cos (2*mathf.pi*frequency*mathf.sin (time.time-initialtime)), 0);

Here are two things to remember: if you use a bit face and want it to face the camera, these values cannot be 0 and 0, but must be PI/2 and –PI/2. Here I'm using eulerangles instead of Euler, because Euler uses degrees, and eulerangles uses radians. We're going to do some math, we're going to use radians now, so we have to eulerangles! or you have to enter a conversion factor for your clasp.

Here you can see a similar animation of my new game, you can change the scale instead of the position in the same way.

Rostlogo (from Gamasutra)

Now we're going to discuss the last type of animation:

Texture compensation

You can use everything you've learned to manipulate 2D texture compensation to create beautiful animated backgrounds. You can see my clumsy imitation of VVVVVV in the Rude Bear Radio and its main interface. Grab a bit face, attach a repeating texture to it, write a fixedupdate () function, and adjust according to subordinates:

Renderer.material.mainTextureOffset
Renderer.material.color

This causes the wall to slide around and change the color. Finally, if you want to make them look more interesting, you can also use Renderer.material.mainTextureScale. This can make a really interesting visual effect, but it's very disruptive, don't let it affect your main gameplay.

Finally, you have to look at the interpolation. This can make animation easier, but I personally think it's best to use a formula in the second part

Http://express.ruanko.com/ruanko-express_56/tech-overnight5.html

As a 3D cross-platform game engine, unity has many advantages over other 2D game development tools (such as cocos2d, cocos2d-x, etc.), such as visualization, WYSIWYG, such as cross-platform, open plug-in platforms, and more. As a beginner, simply share the experience of Unity3d making 2D animations.

There are several ways to make 2D animations in Unity3d:

1. Animation frame sequence

As a common method, it is believed that many developers will use it. Like cocos2d, you can use animated frames to move your character in unity. Example code:

Using unityengine;using System.collections;public class Animatedemo:monobehaviour {public texture[] Frames;public float framespersecond=10;private int index;private float dtime=0;//Use this for initializationvoid Start () {}//Update I s called once per Framevoid Update () {animaone (); Animaalways ();} void Animaalways () {int nowindex= (int) (Time.time *framespersecond)% frames. Length;if (index!=nowindex) {Index  = Nowindex;renderer.material.maintexture = Frames[index];}} void Animaone () {dtime+=time.deltatime;if (dtime>1/framespersecond) {dtime-=1/framespersecond; Renderer.material.mainTexture = Frames[++index];if (index+1>=frames. Length) {}}}}

Here the code is very detailed, has not been executed, by the time the animation frame according to this idea can be easily implemented. The Animaone method enables other controls to be implemented at the last frame of the animation, while the Animaalways method loops through the animation.

2. Animation rendering

In some cases where animation frames are too much or too wasteful, we will animate the animation on a single image and control where the camera or material renders the image. Personally think this method is more suitable for data, tag dynamic display.

For example:

Public Texture imgtexture; Affirm a picture Vector2 scalevec2=new Vector2 (0.1f,1);//control the area of the rendered picture renderer.material.maintexture= imgtexture;// Animation rendering Implementation Renderer.sharedMaterial.SetTextureScale ("_maintex", SCALEVEC2);

3, the above introduced a simple animation effect, in fact, in the game, we often want to make the game characters move up, displacement, rotation, and so on.

In unity, the displacement and rotation of an object without a rigid body is controlled by the Transform property. The transform has position and rotation properties, and unity provides methods for normal rotation and displacement. The most common use is to control the action of object by coordinate increment. The tricky point here is relative displacement and absolute displacement. So take extra care when doing object movement, relative world coordinates or the coordinates of its parent.

Next itween is to do 2D animation more commonly used plug-ins. Its official website and other blogs on the use of methods have a more detailed introduction. The point here is about Itween.hash (). Itween provides a Hash table that makes simple animations more natural and diverse. Hash parameters are slightly different depending on the Itween method.

More commonly used:

    • X, Y, Z, indicating the amount of target Vectore3;
    • Time, times;
    • Easetype, transition mode, smoothing, straight line, or other;
    • Incomplete, the action or method of the current Itween animation end call, and so on.

Unity3d Beginner's 2D animation system

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.