你将学到
1. 如何设置角色的(血量)UI;
2. 如何为UI添加脚本,以控制角色的受伤、死亡;
2. 如何实现敌人攻击角色?
设置角色Health UI
为Health UI添加脚本
该脚本关联了显示角色血量的UI,并编写了角色受伤以及角色死亡的方法。
敌人攻击角色的脚本
如何实现敌人攻击角色?借助物理碰撞检测。拟实现当敌人碰撞到角色时,角色受伤,血量减少10,当血量小于或等于0时,角色死亡。因此,首先需要获取角色GameObject和角色的血条。其次,根据碰撞检测,判断敌人是否发出攻击。
/* 敌人攻击角色:如果敌人碰撞到角色,则发生攻击
* 碰撞检测:OnTriggerEnter和OnTriggerExit函数
* 敌人攻击角色时须判断角色的血量,当血量为0即角色死亡时,需要停止攻击
*/
* 碰撞检测:OnTriggerEnter和OnTriggerExit函数
* 敌人攻击角色时须判断角色的血量,当血量为0即角色死亡时,需要停止攻击
*/
代码逻辑如下:
using UnityEngine;
using System.Collections;
public class EnemyAttack : MonoBehaviour {
public GameObject player;
public PlayerHealth playerHealth;
public int amount = 10;
bool playerInRange;
void Awake() {
player = GameObject.FindGameObjectWithTag("Player");
playerHealth = player.GetComponent<PlayerHealth>();
}
void OnTriggerEnter(Collider other) {
if (other.gameObject == player) {
playerInRange = true;
}
}
void OnTriggerExit(Collider other) {
if(other.gameObject.tag == "Player"){
playerInRange = false;
}
}
void Update() {
if (playerInRange) {
Attack();
}
playerInRange = false;
}
void Attack() {
playerHealth.TakeDamage(amount);
}
}
效果如下:
下面继续为上面的脚本添加其他的函数或属性,让敌人和角色交互时有更有趣的效果,完整代码如下:
using UnityEngine;
using System.Collections;
public class EnemyAttack : MonoBehaviour {
public GameObject player;
public PlayerHealth playerHealth;
//EnemyHealth enemyHealth;
public int attackDamage = 10;// 角色每受到攻击减少的血量
bool playerInRange;
// 敌人攻击的时间间隔
public float timeBetweenAttacks = 0.5f;
// 计时器
float timer;
Animator anim; // playerAnimator
void Awake() {
player = GameObject.FindGameObjectWithTag("Player");
playerHealth = player.GetComponent<PlayerHealth>();
//enemyHealth = GetComponent<EnemyHealth>();
anim = GetComponent<Animator>();// anim = player.GetComponent<Animator>();
}
void OnTriggerEnter(Collider other) {
if (other.gameObject == player) {
playerInRange = true;
}
}
void OnTriggerExit(Collider other) {
if(other.gameObject.tag == "Player"){
playerInRange = false;
}
}
void Update() {
timer += Time.deltaTime;
if (timer >= timeBetweenAttacks && playerInRange && playerHealth.currentHealth > 0/* && enemyHealth > 0*/ )
{
Attack();
}
//playerInRange = false;
if (playerHealth.currentHealth <= 0)
{
anim.SetTrigger("PlayerDead");
}
}
void Attack() {
timer = 0f;
if (playerHealth.currentHealth > 0)
{
playerHealth.TakeDamage(attackDamage);
}
}
}