敌人攻击player功能完成;
首先给敌人加入sphere collider这个collider跟之前的那个作用不同,之前是用来承受player的子弹攻击,这个是敌人的攻击范围,要把is Trigger选上。用OnTriggerStay()函数。
把is Trigger选上之后就会发生一种情况:player的子弹会在sphere collider这个上面碰撞,而这个是我们的敌人攻击范围的collider,范围大于之前的,这是一个bug。
所以要采取一种方法来解决这个bug。如图:
然后把下面这个选择取消就可以了。。。这样就不会影响之前的collider承受攻击了。
给敌人加入脚本enemyattack()完成对player的攻击。
using UnityEngine;
using System.Collections;
public class enemyattack : MonoBehaviour {
private float attack = 10;//攻击力
public float attacktime = 1;//攻击时间
private float timer ;//计时器
private enemyhealth eh;
void Start () {
timer = attacktime;
eh=this.GetComponent<enemyhealth>();
}
// Update is called once per frame
void Update () {
}
void OnTriggerStay(Collider other)
{
timer += Time.deltaTime;
if (other.tag == Tag.player&&eh.hp>=0)
{
if (timer > attacktime)
{
timer =0;
// other.SendMessage("damage", attack);
other.GetComponent<health>().damage(attack);//传递攻击给player的health
}
}
}
}
然后对之前的player的health代码也做一些修改。
主要是加入了player的音效(音效方法和敌人的加入音效方法一样)和死亡后的一些处理,这里没有写游戏存档等功能,只是用 Time.timeScale = 0f;//死后游戏暂停。
using UnityEngine;
using System.Collections;
public class health : MonoBehaviour {
private float hp = 100;
private float time = 3;
private float timer;
private Animator anim;
private SkinnedMeshRenderer skin;
private float changetime = 5;//受伤变化时间
private gunshoot gun;
public AudioClip playerhurt;//
private playermove playermoveee;
void Start () {
anim = this.GetComponent<Animator>();
skin = this.GetComponentInChildren<SkinnedMeshRenderer>();
playermoveee = this.GetComponent<playermove>();
gun = this.GetComponentInChildren<gunshoot>();
//this. skin = transform.Find("Player").renderer as SkinnedMeshRenderer;//另个查找方法,这个也可以用
}
void Update () {
//if (Input.GetMouseButtonDown(0))//测试时候用的鼠标点击来测试player受伤效果。。。
//{
// damage(30);//每次受伤30点
//}
skin.material.color = Color.Lerp(skin.material.color, Color.white, changetime * Time.deltaTime);//皮肤由受伤后的颜色变成白色
}
public void damage(float damagevalue)
{
if (hp <= 0)
return;
AudioSource.PlayClipAtPoint(playerhurt,transform.position,0.9f);//主角受伤声音
skin.material.color = Color.red;//受到伤害皮肤变红色
hp -= damagevalue;
print("敌人攻击次数");
if (hp <= 0)
{
audio.Play();//死亡音效
anim.SetBool("Death",true);//死亡动画
playermoveee.enabled = false;//死后不能控制移动
gun.enabled = false;
StartCoroutine("gameover");
}
}
IEnumerator gameover()
{
yield return new WaitForSeconds(3f);
Time.timeScale = 0f;//死后游戏暂停
}
}
至此,敌人攻击player的功能就完成了。