首先你需要考虑你的敌人应该如何行动,只是并排走或找到敌人作为导航。
我在统一网站上找到了这个脚本:
使用 UnityEngine;
使用 System.Collections;
公共类 EnemyAttack : MonoBehaviour
{
公共浮动时间BetweenAttacks = 0.5f; // 每次攻击之间的时间(以秒为单位)。
公共 int 攻击伤害 = 10; // 每次攻击带走的生命值。
Animator anim; // Reference to the animator component.
GameObject player; // Reference to the player GameObject.
PlayerHealth playerHealth; // Reference to the player's health.
EnemyHealth enemyHealth; // Reference to this enemy's health.
bool playerInRange; // Whether player is within the trigger collider and can be attacked.
float timer; // Timer for counting up to the next attack.
void Awake ()
{
player = GameObject.FindGameObjectWithTag ("Player");
playerHealth = player.GetComponent <PlayerHealth> ();
enemyHealth = GetComponent<EnemyHealth>();
anim = GetComponent <Animator> ();
}
//OntriggerEnter 和 On triggerExit 每次玩家进入时敌人都会跟随敌人碰撞并在玩家退出时停止
void OnTriggerEnter(对撞机其他)
{
// 如果进入的对撞机是玩家...
if(other.gameObject == 玩家)
{
// ... 玩家在范围内。
playerInRange = true;
}
}
void OnTriggerExit (Collider other)
{
// If the exiting collider is the player...
if(other.gameObject == player)
{
// ... the player is no longer in range.
playerInRange = false;
}
}
void Update ()
{
// Add the time since Update was last called to the timer.
timer += Time.deltaTime;
// If the timer exceeds the time between attacks, the player is in range and this enemy is alive...
if(timer >= timeBetweenAttacks && playerInRange && enemyHealth.currentHealth > 0)
{
// ... attack.
Attack ();
}
// If the player has zero or less health...
if(playerHealth.currentHealth <= 0)
{
// ... tell the animator the player is dead.
anim.SetTrigger ("PlayerDead");
}
}
void Attack ()
{
// Reset the timer.
timer = 0f;
// If the player has health to lose...
if(playerHealth.currentHealth > 0)
{
// ... damage the player.
playerHealth.TakeDamage (attackDamage);
}
}
}