Unity3D塔防游戏基本功能实现
塔防游戏是我们熟知的一种游戏类型,接下来讲解它具体功能的实现
1.敌人的出生点和终点
- 分别创建两个空物体,分别为起点和终点
- 随后通过导航网格进行烘培
- 随后调用脚本,代码如下
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyManager : MonoBehaviour { // Start is called before the first frame update public GameObject EnemyPre; private float timer = 0; // Update is called once per frame void Update() { timer += Time.deltaTime; if(timer>2) { timer = 0; Instantiate(EnemyPre, transform.position, transform.rotation); } } }
2.敌人
- 敌人拥有血量,在接触到终点后消失
- 脚本代码如下
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class EnemyControl : MonoBehaviour { private Transform EndPoint; private NavMeshAgent agent; private int hp = 10;//生命值 // Start is called before the first frame update void Start() { EndPoint = GameObject.Find("EndPoint").transform; agent = GetComponent<NavMeshAgent>(); agent.SetDestination(EndPoint.position); } // Update is called once per frame void Update() { //计算敌人和终点的距离来判断敌人是否要销毁 float dis = Vector3.Distance(transform.position, EndPoint.position); if(dis<0.5f) { Debug.Log("敌人跑掉了"); Destroy(gameObject); } } public void GetDamage() { hp--; if(hp<=0) { Destroy(gameObject); } } }
3.塔的放置
- 设置一块区域为放置区,专门放置炮台,敌人不能经过放置区
- 脚本代码如下
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FloorControl : MonoBehaviour { // Start is called before the first frame update public GameObject TowerPre; //在地板上单击鼠标左键调用 private void OnMouseUpAsButton() { if(transform.childCount==0) { GameObject tower = Instantiate(TowerPre, transform.position, Quaternion.identity); tower.transform.SetParent(transform); } } }
4.子弹轨迹
- 发射后一直跟着敌人,直到敌人死亡或消失,随后自己消失
- 脚本代码如下
-
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BulletControl : MonoBehaviour { public EnemyControl enemy; // Update is called once per frame void Update() { if(enemy!=null) { float dis = Vector3.Distance(transform.position, enemy.transform.position); if(dis>0.5f) { transform.LookAt(enemy.transform); //向前移动 transform.Translate(Vector3.forward * 3 * Time.deltaTime); } else { enemy.GetDamage(); Destroy(gameObject); } } else { Destroy(gameObject); } } }