(一)如何知道小兵是否移动到箭塔范围之内,添加碰撞体来检测
(二) 给箭塔添加标签,区别箭塔类型是敌方箭塔还是我方箭塔
(三)创建脚本,当攻击对象移动到箭塔范围之内把其添加到集合里,否则将其移除集合。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tower : MonoBehaviour {
//定义箭塔类型
public int towerType;
//创建一个集合,当小兵移动到箭塔范围之内把其添加到集合里,否则将其移除集合
public List<GameObject> listSolider = new List<GameObject>();
//创建一个集合,当英雄移动到箭塔范围之内把其添加到集合里,否则将其移除集合
public List<GameObject> listHero = new List<GameObject>();
void Start()
{
//有了标签为什么还要定义int,主要是跟小兵类型有个对应
//防止我方箭塔去攻击我方小兵
if (this.gameObject.tag.Equals("Tower"))
{
towerType = 0;//我方箭塔
}
else
{
towerType = 1;//敌方箭塔
}
}
//小兵进入到箭塔范围,箭塔从集合中找攻击目标
private void OnTriggerEnter(Collider other)
{
//进入箭塔是英雄
if (other.gameObject.tag == "Player")
{
listHero.Add(other.gameObject);
}
else
{
//进入箭塔是小兵
SmartSolider solider = other.GetComponent<SmartSolider>();
//当小兵不为空时,判断小兵与箭塔类型是否一致,不一致表示可以攻击
if (solider && solider.type != towerType)
{
listSolider.Add(other.gameObject);//小兵放在可攻击的列表内
Debug.LogError(listSolider.Count);
}
}
}
//人物退出范围,移除列表
private void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Player")
{
listHero.Remove(other.gameObject);
}
else
{
listSolider.Remove(other.gameObject);
}
}
}