现在敌人的collider和rigidbody都有了,说明可以发生碰撞了,下面就用player攻击敌人。
首先给敌人加一个脚本;enemyhealth();
<pre name="code" class="csharp">using UnityEngine;
using System.Collections;
public class enemyhealth : MonoBehaviour {
private float hp = 100;
private Animator ani;
private NavMeshAgent nav;
private enemymove enemymo;
public AudioClip deathclip;//定义死亡声音
public ParticleSystem particlesystem;
private CapsuleCollider cclolider;
void Start () {
ani = this.GetComponent<Animator>();
nav = this.GetComponent<NavMeshAgent>();
enemymo = this.GetComponent<enemymove>();
cclolider = this.GetComponent<CapsuleCollider>();
particlesystem=this.GetComponentInChildren<ParticleSystem>();
}
void Update () {
//if (this.hp <= 0)//实现死亡之后下移然后消失
//{
// transform.Translate(Vector3.down*Time.deltaTime*0.5f);//死后下移
// if(transform.position .y<=-10)//当下移动到3时就销毁敌人
// {
// Destroy(this.gameObject, 2f);
// }
//}
}
public void enemydamage(float damage,Vector3 hitposition)//hitposition 是指射击效果的位置
{
hp -= damage;
audio.Play();
particlesystem.transform.position = hitposition;//指射击粒子效果的位置
particlesystem.Play();
if (hp <= 0)
{
print("siwang");
Death();
}
}
void Death()
{
enemymo.enabled = false;
nav.enabled = false;
ani.SetBool("Death",true);
AudioSource.PlayClipAtPoint(deathclip,transform.position,0.5f);//死亡声音播放(使用的静态)
Destroy(this.gameObject, 2f);
}
}
上面代码里的 public void enemydamage(float damage,Vector3 hitposition)是由player的gunshoot()脚本传递过来的(如下图)。只要在激光的位置加入判断碰撞的代码就可以(attack,hitinfo.point)分别传递了敌人enemyhealth()脚本里的(float damage,Vector3 hitposition)这两个值。。。这样就可以实现攻击敌人到死亡的功能了。
敌人受伤和死亡都需要播放声音,只能定义一个死亡声音(脚本里的 public AudioClip deathclip;//定义死亡声音),另个用unity本来的audio source,如下图;
攻击敌人会有受伤的粒子效果:
如enemyhealth()代码的 particlesystem.transform.position = hitposition;//指射击粒子效果的位置。。。。。 particlesystem.Play();这个是播放粒子。。。。