美文网首页
unity官方案例--坦克大战(五)

unity官方案例--坦克大战(五)

作者: 随便走走侃侃 | 来源:发表于2017-06-02 17:50 被阅读193次

在名为Model的文件夹中找到Shell模型,将其拖入Hierarchy面板中,怎加Capsule Collider组件到Shell对象当中,将Capsule Collider的Is Trigger属性勾选上,设置Direction属性为z-Axis,Center改为(0,0,0.2),Radius改为0.15,Height为0.55。

图5.1  Capsule Collider属性 图5.2  子弹胶囊体

增加一个刚体(Rigidbody)组件到Shell对象当中,在Prefabs文件夹中找到ShellExplosion预制体,将其拖入到Shell对象,并对ShellExplosion对象的AudioSource组件的添加声音,文件名为ShellExplosion,将Play On Awake的勾勾去除。重新选择Shell对象,增加一个Light组件。

下面,我们给Shell对象新建一个名为ShellException的脚本,脚本主要实现以下几个功能

1.攻击

2.受攻击坦克受到伤害,

3受攻击坦克受到冲击波的影响

4.声音和粒子效果

5.整理剩下的游戏对象

下面我们逐个进行实现

首先定义一个计算伤害的函数

private float CalculateDamage(Vector3 targetPosition) {

Vector3 explosionToTarget = targetPosition - transform.position;//构建一个三维坐标,存储目标到炸弹的向量

float explosionDistance = explosionToTarget.magnitude;//计算爆炸点到目标的距离

float relativeDistance = (m_ExplosionRadius - explosionDistance) / m_ExplosionRadius;//计算伤害比例

float damage = relativeDistance * m_MaxDamage;

damage = Mathf.Max(0f, damage);//伤害值最小为0;

return damage;

}

调用OnTriggerEnter函数,官方文档对这个文档的解释是:This message is sent to the trigger collider and the rigidbody (or the collider if there is no rigidbody) that touches the trigger.

Notes: Trigger events are only sent if one of the colliders also has a rigidbody attached. Trigger events will be sent to disabled

MonoBehaviours, to allow enabling Behaviours in response to collisions.(自己翻译:这些信息发送给勾选了Is trigger的碰撞体或者是刚体,然后触碰到标签。注意,标签事件只有当其中一个碰撞体为刚体时才会有反应。)


private void OnTriggerEnter(Collider other) {      

Collider[] colliders = Physics.OverlapSphere(transform.position, m_ExplosionRadius, m_TankMask);//返回指定爆炸半径范围内的碰撞体    

   for (int i = 0; i < colliders.Length; i++) {          

        Rigidbody targetRigidbody = colliders[i].GetComponent();//找到目标的rigidbody                            if(!targetRigidbody){                continue;        }            //增加冲击波作用力            targetRigidbody.AddExplosionForce(m_ExplosionForce, transform.position, m_ExplosionRadius);            TankHealth targetHealth = targetRigidbody.GetComponent();//找到TankHeath脚本,将其关联到rigidbody当中。

if (!targetHealth)

continue;

float damage = CalculateDamage(targetRigidbody.position);

targetHealth.TakeDamage(damage);//将这个伤害作用于坦克

}

m_ExplosionParticles.transform.parent = null;//不解除子弹的粒子系统???

m_ExplosionParticles.Play();//粒子系统发挥作用

m_ExplosionAudio.Play();//爆炸发声;

ParticleSystem.MainModule mainModule = m_ExplosionParticles.main;

Destroy(m_ExplosionParticles.gameObject, mainModule.duration);

Destroy(gameObject);//消除子弹

public void start(){

Destrop(gameObject,m_MaxLifeTime);

}

完成ShellException脚本后,将Shell的子对象ShellException拖入到ShellException脚本的Explosion Particles和Exception Audio当中。将公共参数Tank Mask改为Player。 将Shell对象拖入到Prefabs文件夹当汇总,然后保存为一个Prefabs。

图5.3  ShellException参数设置

保存场景,将Shell从hierarchy面板中删除。

相关文章

网友评论

      本文标题:unity官方案例--坦克大战(五)

      本文链接:https://www.haomeiwen.com/subject/chbrvttx.html