本文主要是介绍2.8.2 发射子弹,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
http://book.2cto.com/201410/47221.html
将新敌人放到场景中,运行游戏,会发现新敌人缓缓向前,但不会做其他事情。我们接下来会为其添加一点新功能,使其可以向主角发射子弹,更有威胁。
使用rocket.fbx创建一个新的子弹Prefab,命名为EnemyRocket,再为其创建一个新的材质,使用rocket2.png作为贴图,使敌人的子弹看上去与主角的不同一些。
为敌人子弹添加Rigidbody和Box Collider 组件并正确设置。
为敌人子弹新建一个名为EnemyRocket的Tag。
创建EnemyRocket.cs脚本,它将继承Rocket类的大部分功能,我们只需要略修改一下OnTriggerEnter方法,使其只能与主角飞船发生碰撞,如下所示
using UnityEngine;
using System.Collections;[AddComponentMenu("MyGame/EnemyRocket")]
public class EnemyRocket : Rocket
{void OnTriggerEnter( Collider other ){if ( other.tag.CompareTo("Player") != 0 )return;Destroy( this.gameObject );}
}
将EnemyRocket脚本指定给敌人子弹的Prefab。
在Inspector窗口设置EnemyRocket 组件,降低敌人子弹的移动速度,增加生存时间,如图2-29所示。
接下来关联新敌人和子弹,打开SuperEnemy.cs脚本,修改代码如下:
using UnityEngine;
using System.Collections;[AddComponentMenu("MyGame/SupperEnemy")]public class SuperEnemy : Enemy
{public Transform m_rocket;protected float m_fireTimer = 2; // 控制发射子弹的时间间隔protected Transform m_player; // 用来指向主角的飞船public AudioClip m_shootClip; // 播放射击的声音protected AudioSource m_audio; // 声音源组件,用于播放声音void Awake() // 继承自MonoBehaviour,它会在游戏体实例化时执行一次,并先于Start方法。{GameObject obj = GameObject.FindGameObjectWithTag("Player"); // 使用FindGameObjectWithTag函数获得主角游戏体实例if(obj != null){m_player = obj.transform;}// m_audio = this.GetComponent<AudioSource>();}<span style="white-space:pre"> </span>// Use this for initialization//void Start () { // 这里一定要注释 Start()函数
<span style="white-space:pre"> </span>//}
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>// Update is called once per frame
<span style="white-space:pre"> </span>protected override void UpdateMove() {m_fireTimer -= Time.deltaTime;if(m_fireTimer <= 0){m_fireTimer = 2;if(m_player != null){Vector3 relativePos = m_transform.position - m_player.position;Instantiate(m_rocket,m_transform.position, Quaternion.LookRotation(relativePos)); // 使子弹在初始化的时候,朝向主角的方向m_audio.PlayOneShot(m_shootClip); // 播放射击声音}}// 在SuperEnemy这个类中,使用了 override 标识符,表示这是一个重写的方法。// 虽然SuperEnemy这个类没有其他成员,但它继承了Enemy类的其他全部功能// 前进// m_transform.Translate(new Vector3(0, 0, m_speed * Time.deltaTime));m_transform.Translate(new Vector3(0, 0, -m_speed * Time.deltaTime ));//}
}
m_fireTimer属性用来控制发射子弹的时间间隔。
m_player属性用来指向主角的飞船。
Awake方法继承自MonoBehaviour,它会在游戏体实例化时执行一次,并先于Start方法。我们在这里使用FindGameObjectWithTag函数获得主角的游戏体实例。
Quaternion.LookRotation使子弹在初始化时朝向主角的方向。
选择新敌人Prefab,在Inspector窗口选择Rocket属性,与敌人子弹的Prefab关联,如图2-30所示。

这篇关于2.8.2 发射子弹的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!