[Unity3D] Unity3D game development-tower defense game project (I), unity3d Game Development

Source: Internet
Author: User

[Unity3D] Unity3D game development-tower defense game project (I), unity3d Game Development

If you like my blog, please remember my name: Qin Yuanpei. My blog address is blog.csdn.net/qinyuanpei

Reprinted please indicate the source, Author: Qin Yuanpei, the source of this article: http://blog.csdn.net/qinyuanpei/article/details/42394949

Hello everyone, I'm Qin Yuanpei. I participated in the CSDN2014 blog Star Selection. You are welcome to vote for me and hope that everyone will continue to support my blog in the new year!

As the first blog in 2015, I would like to thank all of you for your encouragement and support. In the new year, the blogger will try to share more and better original technical articles on game development. I hope you will continue to pay attention to and support the blogger's blog. So today, the blogger wants to share with you a project case of Anti-tower games. In general, tower guard games refer to a type of strategy games that build blocks or similar buildings on maps to prevent enemy attacks. From this concept, we can quickly extract three elements:Map (scene), enemy, and Fort (Defense Unit ).After we extracted these three elements, the anti-tower games now become a description like this:EnemyFollowMapDesigned path attack, used by gamersDefense UnitA type of defensive strategy game. What are the classic anti-tower games? For example, the most familiar "Plants vs. Zombies" and "defending radish" are all classic games of tower Defense Games. If we extend the range of defensive units in anti-tower games to players, games like League of legends can also be called anti-tower games, because the ultimate goal of the enemy and me camp is to destroy the enemy's defense tower, but both sides of the enemy and me have changed from the fort or monsters to flesh-and-blood figures, coupled with RPG and instant strategy (RTS) the mixed penetration of other elements makes such a game from a simple anti-tower game to a highly playable game (Oh, my God, i'm boasting about this game .....). Well, let's try to make a simple anti-tower game. Note that it is a simple anti-tower game. Since the three elements of anti-tower games are:Maps, enemies, and defensive unitsSo let's start designing this game from these three aspects! In this article, we will use the following knowledge:

  • Sprite animation in Unity2D
  • Gizmos, a visual helper class in Unity3D
  • Implementation of path-based search for enemies in anti-tower games
  • Unity3D uGUI Preliminary Exploration
  • Simple AI Algorithms

1. Map

Maps are the most important part of a tower guard game, because maps and enemies directly affect players' strategies. It is a game map extracted from the "defending radish" game. In this map, we can clearly see the path of the monster attack. The monster will launch an attack to our defense unit along the path in the map. So how can we determine the path of a monster attack in the game? First, we can analyze the map. Basically, there are only two types of areas in the map, namely, the area of the defensive unit and the area of the defensive unit. Therefore, we can design the following structure:

 

using UnityEngine;using System.Collections;[SerializeField]public class GridNode : MonoBehaviour {public enum NodeType{CanPlace,CantPlace}public NodeType GridNodeType=NodeType.CanPlace;}

We can see that a NodeType Enumeration type is defined in the GridNode class. This enumeration type has two values. CanPlace indicates that the Unit can be placed, while CantPlace indicates that the unit cannot be placed. In the GridNode class, there is only one member variable of the NodeType type GridNodeType. The default value of this member variable is CanPlace, that is, the defensive unit can be placed. Now the question is, we have found a method that can be used to describe different regions in the map. But where are these regions? Therefore, we need a method to generate these regions. Here we will introduce you to the Gizoms class. Gizmo is a tool class in Unity for visual debugging or auxiliary settings in the scenario view. To put it simply, when we need to implement some visual debugging in the editor environment, we can use the Gizmo class. Therefore, Gizmo painting must be completed in the OnDrawGizmos or OnDrawGizmosSelected function. From the names of these two functions, we can see their differences. OnDrawGizmos are called at each frame, and all Gizmo rendered in Gizmos will be rendered, onDrawGizmosSelected is rendered only when the objects attached to the script are selected. Now, after learning about the basic concepts and usage of Gizmos, let's go back to our game. We just mentioned that we need a method to generate a region so that we can use the GridNode class to describe the attributes of each region. How can we do this? In fact, the idea is to draw a grid on the map, so that the grid can split the whole map into different regions, and then we can use GridNode to describe the attributes of each region. Now 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();DrawColor();DrawPath();}}

In this script, we first define two int-type variables MapSizeX and MapSizeZ, which respectively indicate the size of the mesh to be drawn. Next we will focus on the OnDrawGizmos method. In this method, we define three methods: DrawGrid, DrawColor, and DrawPath. The DrawGrid method is used to draw the map grid, the DrawColor method is used to draw the map area, and the DrawPath method is used to draw the enemy path. First, let's talk about DrawGrid. DrawGrid is responsible for drawing map grids. By default, it is drawn from the origin. To draw a grid, you only need to draw staggered crosslines and vertical lines, here we use the DrawLine method in the Gizmos class. First, we create a blank MeshRoot object in the scenario and attach the GridMap script to the object. Let's take a look at the effect of the painting:


Gizmos provides visual debugging functions, so we can directly see the actual effect in the editor window, so that we can use Unity to draw a map grid. In order to make the lower left corner of the map exactly match the scene origin, the blogger wrote a simple tool class AutoPlace to calculate and adjust the location of the MAP:

Using UnityEngine; using System. collections; public class AutoPlace: MonoBehaviour {// genie Renderer private SpriteRenderer mRenderer; // genie width private float mSpriteWidth; // genie height private float mSpriteHeight; void Start () {mRenderer = GetComponent <SpriteRenderer> (); // calculate the actual size of the spritewidth = mRenderer. sprite. bounds. size. x * transform. localScale. x; mSpriteHeight = mRenderer. sprite. bounds. size. y * transform. localScale. y; // automatically adjust the location of the genie transform. position = new Vector3 (mSpriteWidth/2, mSpriteHeight/2, 0 );}}

Now, let's continue to explain how to generate a region in the map. What is a region in a map? In tower guard games, players usually have to place defensive units only in the area where they can place defensive units. The areas where defensive units can be placed are the areas we will study next. First, we need to create an empty object NodeObject for each grid unit based on the grid drawn in the first step, and attach the GridNode script to the object, if the position of the object on the map can be placed with the defensive unit, we will set its GridNodeType to CanPlace, otherwise it will be set to CantPlace. Here, the real-time bloggers prefer to use the dynamic generation method to add area attributes for each grid unit. But here we want to understand the process, simply create it manually! Haha, but the blogger has manually created 96 empty objects. I think I'm so drunk. Now, we need to set a GridNode Tag for each NodeObject, so that we can get all nodeobjects through tags in the program. Finally, we put all these nodeobjects under the MeshRoot node to make it a sub-node of MeshRoot. Next, we continue to return to the DrawColor method in the GridMap script. In the Awake method of the script, we first obtain all nodeobjects, and then attach the GridNode script to each NodeObject, to determine whether the grid unit can be placed in the defensive unit or not. If it can be placed in the defensive unit, use green to draw a Cube, if you cannot place the defensive unit, draw a Cube in red, so that we can distinguish different areas by color in the editor. Now let's take a look at the actual results:

Now, we can clearly see the distribution of the entire area in the map. The red part is the area where the defensive unit cannot be placed, and the green part is the area where the defensive unit can be placed. You should note that there is a white line in the red area. This line is actually the path of the enemy. Next we will introduce how to generate the path of the enemy. Compared with the generation of grids and regions, path generation is much simpler. Because the path only needs to focus on the start point, end point, and node. How can we create a new empty object named PathRoot in the scenario, and then create an empty object named PathNode in the red area for the start, end, and node respectively, and set its Tag to PathNode.

Now let's take a look at a script called PathNode. This script describes the relationship between 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, ThisNode points to the node itself, ThatNode points to the next node, and provides a method to set the next node, SetNode. Now, we can attach this script to each PathNode and use the editor to quickly specify ThisNode and ThatNode for each node. Now we know the relationship between each path node. The next thing we need to do is to use Gizmos to draw the path. How can we draw it? From the current node to the next node. Now let's take a look at what the DrawPath method has done:

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 everyone understands. First, we obtain all PathNode Objects Based on tags, and then draw a line segment for each node pointing to the next node based on the PathNode script, create a small Cube for the node. Well, let's take a look at the final effect:

So far, all the map content has been explained. Let's simply summarize, in this part, we have learned how to use the visual assistant class Gizmos to draw grids, regions, paths, and other applications. We mainly use the DrawLine and DrawCube methods.

Well, this project has a lot of content, so the blogger decided to put the enemy article and the defensive unit article in the next article to explain it to everyone, because after writing it in an article, not only do bloggers get tired of writing, but they get tired of reading, so today's content is like this. I hope you will like it! Finally, we will present a project demonstration today:


Daily proverbs: pain or error. It is with these things that we can reach the unknown step by step, isn't it?



If you like my blog, please remember my name: Qin Yuanpei. My blog address is blog.csdn.net/qinyuanpei

Reprinted please indicate the source, Author: Qin Yuanpei, the source of this article: http://blog.csdn.net/qinyuanpei/article/details/42394949

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.