[Unity3d] Research on the Unity3d native2d characteristics of Unity3d game development

Source: Internet
Author: User

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------

Like my blog Please remember my name: Qin Yuanpei , my blog address is Blog.csdn.net/qinyuanpei.

Reprint please indicate the source, this article Qin Yuanpei , this article source: http://blog.csdn.net/qinyuanpei/article/details/40452019

--------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------

Hello everyone, I am Qin Yuanpei, welcome everyone to pay attention to my blog, my blog address is Blog.csdn.net/qinyuanpei. After the Unity4.3 version, Unity3d launched the box2d-based 2D component, making Unity3d a game engine that can support 2D game development. Before Unity3d launched this feature, we have done a lot of research on the use of Unity3d to develop 2D games. So, Unity3d launch 2D component is not a huge breakthrough in essence, because two-dimensional and three-dimensional difference is three-dimensional than two-dimensional more than a z-axis, if we fixed the z axis, then this is a two-dimensional world. Prior to this, we used the orthogonal projection method, which allows the camera to be projected perpendicular to the XY plane, so that the 3D engine can be used to achieve the effect of 2D games. Now that unity can support native 2D game development, why don't we try it? Bloggers have been planning to take time to study the characteristics of Unity3d's native2d, but for various reasons there has been no time to study, so now just use this weekend to study it!


one, Sprite and Sprite Atlas

Although we have Unity3d 2D features as native2d, but in fact natvite is only relative to third-party plug-ins, essentially Unity3d 2D is still part of the category 3D. Sprite (Sprite) is the first component we walk into native2d, so the 2D feature is based on this component. A friend who has studied the development of 2D games should know that elves are actually a poster in the 2D world. Well, let's create a new project to demonstrate how to use the Sprite component! The first exciting feature is that we can decide whether a project is a 3D game or a 2D game when creating a project, and here we choose 2D directly, because what we're going to explore today is Unity3d's native2d feature .


After entering unity we will notice that a 2d/3d option button appears on Unity's toolbar and the 2D button is activated in the current scene, which means that this is a 2D project, which we can find by toggling the button. The native2d of Unity3d is the effect of fixing the z axis of Unity3d, so Unity3d native2d or 3D engine is an implementation under 2D effect in essence.


Bo Master and slave love to find some material on the net, do the following such a scene:


We note that there is one of the most important spriterenderer components in the sprite component, which is responsible for rendering the sprite, and we can specify the rendered resource by specifying the Sprite property. We select one of the picture resources and can see its Properties window:


Where TextureType is used to indicate the type of map, here we choose the type of Sprite, because only this type of map can be supplied to the sprite component for use. Spritemod is used to specify whether the sprite is a single graph or a series of graphs, we notice that this image is a sequence of frame animations, so we should choose the multiple type. Next, we click the Spriteeditor button to open the Sprite editor, which is designed to split these sprite sets into a single picture. If you have read the blogger has just started to learn Unity3d wrote articles, it must be recalled that Bo has used Photoshop to use a frame animation sequence diagram in transduction way, and then by mapping the way to achieve frame animation bar. Isn't that a lot of trouble? No problem, Unity3d's nativie2d provides a wizard editor that can help you get this job done quickly. We open the wizard editor:


You can see that this picture is divided into 16 pictures. One trick here is to get a consistent size tile with the trim button, because the sprite editor can help you determine the bounds of the graph. The advantage of this is that unity can help you generate 16 frames of animation sequences, so you can call a frame animation arbitrarily, but the resource manager does not generate the corresponding files, which can save the project resources size.


Well, next, let's write a script to show how to use this set of sprite animations:

Using unityengine;using System.collections;public class Spritescript:monobehaviour {//Up Wizard collection public sprite[]    Upsprites; Down Wizard Collection Public sprite[] downsprites;//Left Wizard collection public sprite[] leftsprites;//Right Wizard collection public sprite[] rightsprites;// Last used Sprite collection private sprite[] lastsprites;//currently used sprite collection private sprite[] currentsprites;//current frame sequence index private int index=0;// Frames per second private float fps=10;//current experience time private float currenttime=0;//role Current state private playerstate state;//Sprite renderer Private Spriterenderer renderer=null;void Start () {//Initialize role Status state=playerstate.idle;//Initialize Role Wizard set currentsprites=upsprites; lastsprites=currentsprites;//gets the sprite renderer renderer=getcomponent<spriterenderer> ();} void Fixedupdate () {if (Input.getaxis ("horizontal") ==1) {state=playerstate.walk; Setsprites (rightsprites); MoveTo (New Vector2 (Time.deltatime * 2.5f,0)); else if (Input.getaxis ("horizontal") ==-1) {state=playerstate.walk; Setsprites (leftsprites); MoveTo (New Vector2 (-time.deltatime * 2.5f,0)); else if (Input.getaxis ("Vertical") ==1) {State=playerstate.waLk Setsprites (upsprites); MoveTo (New Vector2 (0,time.deltatime * 2.5F));} else if (Input.getaxis ("Vertical") ==-1) {state=playerstate.walk; Setsprites (downsprites); MoveTo (New Vector2 (0,-time.deltatime * 2.5F));} else if (! Input.anykey) {State=playerstate.idle;} Drawsprites (currentsprites);}   The role moves private void MoveTo (Vector2 offest) {//calculates the role position based on the offset float x=transform.position.x + offest.x;   float Y=TRANSFORM.POSITION.Y + offest.y; Use the 2D rigid body assembly to move the sprite this.rigidbody2D.MovePosition (new Vector2 (x, y));}    Sets the current sprite collection private void Setsprites (sprite[] sprites) {currentsprites=sprites;   If the current sprite collection and the last used sprite set are not equal, it indicates that you want to toggle the sprite set if (currentsprites!=lastsprites) {lastsprites=currentsprites;    index=0;}} Draws the current sprite collection private void Drawsprites (sprite[] sprites) {//If the role is in a standing state then the first frame if (State==playerstate.idle) {  Renderer.sprite=sprites[0];    }else{currenttime+=time.deltatime;//If the current time is greater than the frame animation render time, you need to render a new frame animation if (currenttime>1/fps) {//To increase the index and clear the current time by 0 to re-count index+=1;currenttime=0;//causes the index filmstrip to loop if (index>=sprites. Length) {index=0;} }}//Render Renderer.sprite=sprites[index];} #region Role Status Enumeration definition #enum Playerstate{walk,idle} #endregion}
So, let's take a look at the actual operating effect:



This is an animated effect that controls the movement of characters along the top, bottom, left, and right four directions, which we can easily implement. However, our code seems to write a lot of ah, then there is a better way? When Unity3d did not launch the 2D component, we could draw a sprite in the form of a map, and for this kind of frame animation sequence picture, we can use offset to determine where to display the map. However, this method seems to be only useful for common textures, and there is nothing to do with sprites. Bo Master personally or like to use this way, after all, with the wizard editor, transduction is a very simple thing. Next, we will give a generic script that can be used for any continuous frame animation loop playback, suitable for playing in the game relative to the player's static effect, such as the flag flying in the game, flying Birds and so on:

Using unityengine;using System.collections;public class Fightscript:monobehaviour {//Sequence frame animation collection public sprite[] animations;//Current frame sequence index private int index=0;//frames per second public float fps=10;//current experience time private float currenttime=0;//Sprite renderer private Spriterenderer renderer;void Start () {//Get Sprite renderer renderer=getcomponent<spriterenderer> ();} void Fixedupdate () {drawsprite ();} Provides an external interface to make it easy to change the animation public void Setanimations (sprite[] Sprites,int index) {this. Animations=sprites;this.index=index;} Plays the animation according to the Sprite Collection void Drawsprite () {currenttime+=time.deltatime;//If the current time is greater than the frame animation render time, you need to render a new frame animation if (Currenttime>1/fps) {/ /causes the index to increment and clear the current time by 0 in order to re-count the index+=1;currenttime=0;//so that the index Filmstrip loops if (index>=animations.length) {index=0;}}   Render   Renderer.sprite=animations[index];}}
The feature of this script is that the animation can be looped from one frame to the next, as long as a series of frame animation sequences are specified. Below, we add two sprites with attack effects:

What do you think? The effect is good, haha. OK, let's talk about the Sprite Atlas! You can notice that as the project progresses, the picture resources used in the project will become more and more, and the whole game will be bigger and larger if you don't pay attention to the control. To solve this problem, Unity provides a sprite Packer for the packaging of the Sprite atlas. The so-called Sprite Atlas, in fact, is to concentrate the scattered picture resources into a picture Ah, this can reduce the capacity of the image resources. This is actually a bit similar to Ngui inside the atlas, Bo Master in the previous period of time also unpacked "Paladin four" part of the resources, for the game's image resources It is also used in this way to deal with. OK, let's see how to implement the Sprite pack in Unity3d! You first need to enable the Sprite Packer feature in Unity:

Next, open the Sprite Packer window through Window->sprite Packer, then select the picture resource you want to package in the project resource and set its packing tag to the same name as Enemys so that they will be packaged on the same image.

Next we click on the pack, we will find that these images are synthesized in a picture, if we modify any one of the images of packing Tag, then this picture will disappear from the current set of figures.

Well, the first part of the content to this end, we have a little rest, we began the second part of this article: 2D Physical world as Beautiful


Second, 2D physics and box2d

      mentions the 2D game engine and cannot but say box2d. Box2D is a C + + engine used to simulate 2D rigid body objects, usually used as a physics engine in the 2D game engine, so it can be found in many game engines, and Unity3d's native2d is the use of the box2d engine. The details of this engine can be understood on their own, in short if the game world lacks a collision, then game world is too boring! Life is like an angry bird, and when you fail, there is always a pig laughing. The face of We still have to face, even in the reality of hitting the wall was beaten badly, but this life is always worth our chase, because the cold lonely life, after all, is not as vigorous as death. Well, gossip less, let's learn the next Unity3d in 2D physics. In Unity3d, all 2D physics-related components are placed in physics  2d this parent menu, so we can find the relevant 2D physical components here. There are three main types of 2D physical components available in unity: Rigid bodies, colliding bodies, and joints. Now we just have to focus on the rigid body and the collision body. Estimated 2D Physics This is a lot of friends will feel it doesn't matter, big can't write Bai. Bo Master before and a friend, he did a hit feeling good ARPG hand tour from beginning to end never used collision, all the logic is almost written by themselves, because 2D physics is simple ah, as long as the distance can be calculated. But as a moral integrity programmer, in a deep understanding of the meaning of not repeating the production of wheels, will also persist in writing their own collision detection? So we're going to use the components provided by unity directly. We first add a rigidbody rigidbody to the protagonist and tick the fixed ANGLG because we do not need to change the angle in the collision process. Again, we don't need gravity, so we need to set gravity angle to 0.


Next we add the box Collider 2D Collider to the protagonist in the scene, two combat characters and one NPC, and write the following script to test the collider and the trigger separately, and here's the detail that if you need a strong effect after an object collision, you need to add a Rigidbody component to the object, Because the effect of force is mutual. The following script is given:

Using unityengine;using System.collections;public class Collisioncheck:monobehaviour {void Oncollisionenter2d ( Collision2d coll2d) {if (coll2d.gameobject.tag== "Fight Player") {Debug.Log ("Please stay away from me, I am practicing the peerless martial arts!");}} void ontriggerenter2d (collider2d coll2d) {if (coll2d.gameobject.tag== NPC Player) {Debug.Log ("Although I am an NPC, I still have a part to play. !");}}}
The collision detection in the physical world is basically the same as the collision detection in the 3D physics world, so you can refer to the official latest API documentation, since there is basically no such part in the API documentation for domestic translation. OK, let's take a look at the running effect!


Well, today's content is like this, I hope you like Ah, why every time after writing blog is so tired ah? Is it because there is a lot of information to be consulted? Do not understand the place you can give me a message, I try to solve, or hope that we can focus on and support bloggers blog, so Bo Master has the courage to write down. All right, that's it!


Daily Proverbs: All the setbacks and pain in life, all the experience, is to make you exercise you. Do not always say that the years are cruel, it is actually gentle you.




--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------

Like my blog Please remember my name: Qin Yuanpei , my blog address is Blog.csdn.net/qinyuanpei.

Reprint please indicate the source, this article Qin Yuanpei , this article source:http://blog.csdn.net/qinyuanpei/article/details/40452019

--------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------


[Unity3d] Research on the Unity3d native2d characteristics of Unity3d game development

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.