人物和怪物的攻击都有CD冷却,在PlayerAttack脚本中添加成员
//冷却倒计时 public float attackTimer; //CD冷却时间 public float coolDown = 2.0f;
修改Update
void Update () { if (attackTimer > 0) attackTimer -= Time.deltaTime; if (attackTimer < 0) attackTimer = 0; if (Input.GetKeyUp (KeyCode.F) && attackTimer == 0) { Attack(); attackTimer = coolDown; } }
运行Game,点击F后,AttackTimer从2到0后才可再次释放攻击。
下面创建怪物的攻击脚本,在Scripts文件夹中选中PlayerAttack,按ctrl+d,赋值一份,重命名为EnemyAttack:
1. 修改类名为EnemyAttack
2. 删除对按键F输入的判断,怪物始终2秒攻击一次玩家
3. 修改Attack内的EnemyHealth为PlayerHeath类
public class EnemyAttack : MonoBehaviour { public GameObject target; //冷却倒计时 public float attackTimer; //CD冷却时间 public float coolDown = 2.0f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (attackTimer > 0) attackTimer -= Time.deltaTime; if (attackTimer < 0) attackTimer = 0; if (attackTimer == 0) { Attack(); attackTimer = coolDown; } } private void Attack(){ if (Vector3.Distance (target.transform.position, transform.position) < 2) { PlayerHealth ph = (PlayerHealth)target.GetComponent ("PlayerHealth"); ph.AddjustCurrentHealth (-10); } } }
运行Game,玩家和怪物靠近时,每隔2秒,玩家掉血10,玩家按下F,怪物掉血10。
但是有个问题,上图可以看到怪物和玩家距离过近,并且有抖动,那是因为EnemyAI里的向玩家移动的代码,没有限制为,当距离大于2的时候,怪物才向玩家移动,将该距离定义为类的全局变量maxDistance,方便进行修改。
//当距离大于2的时候
if (Vector3.Distance (target.position, myTransform.position) > maxDistance) { //怪物向着Player的方向移动 myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
毫无理由的 坚持、坚持、再坚持!