[Unity3d] Unity3d Game Development Tower Defense Game Project Explanation (the)

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 , the source of this article: http://blog.csdn.net/qinyuanpei/article/details/42394949

??

Hello, I am Qin Yuanpei. I participated in the CSDN2014 blog star's selection, welcome everyone to vote for me, at the same time hope that in the new year we can continue to support my blog!

As the first blog in 2015, bloggers first want to thank all the friends for their encouragement and support, in the new Year, Bo will try to share more, better game development of original technical articles, I hope you can continue to focus on and support bloggers blog. Well, today bloggers want to share with you is a project case of tower defense game. In general, tower Defense is a kind of strategy game that builds a fortress or similar building on a map to stop an enemy from attacking. From this concept, we can quickly pull out three elements, namely map (scene), Enemy, Fort (defensive unit). when we pull out such three elements, now the tower defense game becomes such a description, that is, the enemy in accordance with the path of the map designed to attack, the player use defensive units to defend a class of strategy game. What are the classic tower defense games? For example, we are most familiar with the "Plant vs Zombies", "protect the radish" is the Tower Defense game Classic game. If we expand the range of defensive units in the tower defense game to players, then games like League of Legends can also be called Tower Defense games, because the ultimate goal of the enemy camp is to destroy the enemy's defense tower, but both sides from the fort or monster into the flesh and blood of the characters, coupled with role playing (RPG And real-time strategy (RTS) and other elements of the mixed infiltration, so that the game from a simple tower defense game into a very high-play game (God, I actually boast this game ...). Well, then we will try to make a simple tower defense game, note is a simple tower defense game Oh, since the tower defense game three elements are maps, enemies and defensive units , then we start from these three aspects to design this game! In this article, we will use the following knowledge:

    • Sprite animations in unity2d
    • Visual auxiliary classes in Unity3d gizmos
    • The realization of the enemy's path finding in the tower defense game
    • Preliminary exploration of Unity3d Ugui
    • A simple AI algorithm

first, the map chapter

maps are the most important place for players in a tower defense game, because maps and enemies directly affect the player's strategy. It is a game map extracted from the game of "defending Radish" by Bo-master. In this map we can clearly see the path of the monster attack, the monster will follow the path in the map to our defensive units to launch attacks. So, in the game, how do we determine the attack path of the monster? First of all, we can analyze the map, basically there are basically only two types of areas in the map, that is, the area can be placed defensive units and non-placed defensive units of the area two. This allows us to design the following structure:

Using unityengine;using System.Collections; [Serializefield]public class Gridnode:monobehaviour {public enum nodetype{canplace,cantplace}public NodeType Gridnodetype=nodetype.canplace;}

As you can see, we define an enumeration type called NodeType in the GridNode class, which has two values, Canplace indicates that the defensive unit can be placed, and Cantplace indicates that the defensive unit cannot be placed. In the GridNode class, there is only one member variable gridnodetype of the NodeType type, and the default value of the member variable is canplace, which means that the defensive unit can be placed. So, now that's the problem, we've found a way to describe the different areas of the map, but where are these areas? So we need a way to generate these areas. Here is a grand introduction to the Gizoms class, the Gizmo is a tool class used in unity to visualize debugging or auxiliary settings in the scene view. Simply put, we can use the Gizmo class when we need to implement some kind of visual debugging in the editor environment. So the gizmo drawing needs to be done in the Ondrawgizmos or ondrawgizmosselected function. From the names of these two functions we can see the difference between them, Ondrawgizmos is called at every frame, all the gizmos rendered in gizmos will be rendered, and ondrawgizmosselected is only rendered when the object attached to the script is selected. Well, after understanding the basic concepts and usage of gizmos, we go back to our game. We just mentioned that we need a way to generate zones so that we can use the GridNode class to describe the properties of each zone, so what do we do? The idea is to draw a grid on the map so that the grid can split the entire map into different areas, and then we can use GridNode to describe the properties of each area. OK, let's look at the specific script:

Using unityengine;using System.collections;public class Gridmap:monobehaviour {public static gridmap instance=null; public int mapsizex;public int mapsizez; [Hideininspector]public gameobject[] mnodes; [Hideininspector]public gameobject[] mpaths;void awake () {Instance=this;mnodes=gameobject.findgameobjectswithtag (" GridNode "); Mpaths=gameobject.findgameobjectswithtag (" Pathnode ");} void DrawGrid () {gizmos.color=color.blue;for (int i=0;i<=mapsizex;i++) {gizmos.drawline (new Vector3 (i,0,0), new Vector3 (i,mapsizez,0));} for (int j=0;j<=mapsizez;j++) {gizmos.drawline (new Vector3 (0,j,0), New Vector3 (mapsizex,j,0));}} void Drawcolor () {if (mnodes==null) Return;foreach (Gameobject go in mnodes) {Vector3 mpos=go.transform.position;if (go. Getcomponent<gridnode> ()!=null) {if (go. Getcomponent<gridnode> (). Gridnodetype==gridnode.nodetype.canplace) {Gizmos.color=color.green;} else if (go. Getcomponent<gridnode> (). Gridnodetype==gridnode.nodetype.cantplace) {gizmos.color=color.red;} Gizmos.drawcube (Mpos,neW Vector3 (1,1,1));}}} void DrawPath () {gizmos.color=color.white;if (mpaths==null) Return;foreach (Gameobject go in mpaths) {if (go. Getcomponent<pathnode> ()!=null) {Pathnode node=go. Getcomponent<pathnode> (); if (node. Thatnode!=null) {gizmos.drawline (node.transform.position,node. ThatNode.transform.position);}}} void Ondrawgizmos () {DrawGrid ();D rawcolor ();D Rawpath ();}}

In this script, we first defined two variable mapsizex,mapsizez of type int, which are used to indicate the size of the mesh that needs to be drawn. Let's focus on the Ondrawgizmos method, where we define 3 methods DrawGrid, Drawcolor, and DrawPath. Where the DrawGrid method is responsible for drawing the map grid, the Drawcolor method is responsible for drawing the map area, DrawPath method is responsible for plotting the enemy pathfinding path. First of all, Drawgrid,drawgrid is responsible for drawing the map grid, starting from the origin by default, to draw the mesh only need to draw staggered horizontal and vertical lines, Here we use the DrawLine method under the Gizmos class we first create a meshroot empty object in the scene, attach the Gridmap script to the object, let's look at the effect of the drawing below:


Because gizmos provides us with a visual debug function, we can see the actual effect directly in the editor window, so that we use unity to draw the grid of the map. To make the bottom left corner of the map exactly match the scene origin, the blogger writes a simple tool class autoplace to calculate and adjust the location of the map:

Using unityengine;using System.collections;public class Autoplace:monobehaviour {//elf renderer private Spriterenderer mrenderer;//elf width private float mspritewidth;//elf height private float mspriteheight;void Start () {mrenderer=getcomponent <SpriteRenderer> ();//Calculate the actual size of the Genie mspritewidth=mrenderer.sprite.bounds.size.x * transform.localscale.x; MSPRITEHEIGHT=MRENDERER.SPRITE.BOUNDS.SIZE.Y * transform.localscale.y;//automatically adjusts the position of the sprite Transform.position=new Vector3 ( mspritewidth/2,mspriteheight/2,0);}}

OK, let's go on to the generation of areas in the map. What is the area in the map? In tower defense games, players usually have to place defensive units in the area where the defensive unit can be placed, so those places where defensive units can be placed are the areas we are going to study next. We first need to create an empty object Nodeobject for each grid unit based on the mesh drawn in the first step, and attach a GridNode script to the object, if the object is located on a map where the defensive unit can be placed, Then we will set its gridnodetype to Canplace, otherwise it will be set to Cantplace. In fact, bloggers here are more like to use the dynamic generation of the way to add the regional properties for each grid unit, but here we understand the process, simply create it manually! Haha, but Bo master incredibly manually created 96 empty objects, think all feel drunk ah. Well, we need to set a gridnode tag for each nodeobject, so we can get all the nodeobject through the tag in the program. Finally, we put all these nodeobject under the Meshroot node, making it a child of meshroot. Now, let's go back to the Drawcolor method in the Gridmap script, we first get all the nodeobject in the awake method of the script, and then add the Nodeobject script based on each GridNode object, To determine whether the grid unit can be placed in a defensive unit or not to put defensive units, if you can put defensive units to draw a cube with green, if you can not put defensive units in red to draw a cube, so that our editor can be based on color to distinguish between different regions. Well, let's take a look at the actual effect below:

OK, now you can clearly see the entire map of the distribution of the area, the red part of the area is not placed defensive units, the green part can be placed in the defensive unit area. You should notice that there is a white line in the red area, and this floss is actually the path of the enemy. Well, let's talk about the generation of the enemy pathfinding path. The path generation is much simpler than the generation of grids and regions. Because the path only needs to focus on the starting point, end point, and node. Specifically how to do it, first we create a new empty object in the scene named Pathroot, next we in the red area for the starting point, the end point and the node to create an empty object, named Pathnode, and set its tag to Pathnode.

Well, next, let's look at a script called Pathnode, a script that describes the relationships of each path node, similar to the structure of a linked list:

Using unityengine;using System.collections;public class Pathnode:monobehaviour {public Pathnode thisnode;public Pathnode thatnode;public void Setnode (Pathnode _node) {if (thatnode!=null) {thatnode.thisnode=null; Thatnode=_node;_node. Thisnode=this;}}}

In this script, we let Thisnode point to the node itself, Thatnode refers to the next node, and provides a method setnode to set the node. Now we attach this script to each pathnode, and the editor allows you to quickly specify Thisnode and Thatnode for each node. So, now the relationship between the various path nodes we have been very clear, the next thing is to do is to use gizmos to draw the path, how to draw it? Point to the next node from the current node. Now let's take a look at what the DrawPath method has done specifically:

void DrawPath () {gizmos.color=color.white;if (mpaths==null) Return;foreach (Gameobject go in mpaths) {if (go. Getcomponent<pathnode> ()!=null) {Pathnode node=go. Getcomponent<pathnode> (); if (node. Thatnode!=null) {   gizmos.drawline (node.transform.position,node. ThatNode.transform.position);} Gizmos.drawcube (node.transform.position,new Vector3 (0.25f,0.25f,0.25f));}}

I believe we all understand, we first obtained all the Pathnode object according to tag, and then according to the Pathnode script to draw each node point to the next node segment, while drawing a small cube for the node. Well, let's look at the final effect:

So far, all the information about the map is finished, let us briefly summarize, in this part, we mainly learn the visual auxiliary class gizmos in the plot grid, region, path and other aspects of the application, the main use of DrawLine and Drawcube two methods.

Well, the content of this project is more, so Bo Master decided to the enemy, Defense unit chapter in the next article to explain, because in an article written, not only bloggers will be more tired, read it will be more tired ah, so today's content is so, I hope you like Ah! Finally for everyone to send the project today:


Daily Proverbs: Pain or wrong, it is burdened with these, we can step-by-step to reach the unknown front, is not it?



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/42394949??

?????

[Unity3d] Unity3d Game Development Tower Defense Game Project Explanation (the)

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.