七、射击功能
1.创建空命名为Shot Spawn为子弹挂载体,设置位置,获取子弹预制体,挂载体相对位置,实例化。(射出很多的子弹是什么问题,是因为FireRate未进行值设置,会导致发射频率很快,但可以加入进化版的改进内容。)
在PlayerManager.cs中添加下列代码
public GameObject shot; //获取子弹预制体
public Transform shotSpawn; //子弹生成的父类
public float fireRate; //子弹发射率
private float nextFire; //计时器,下一次发射
void Update()
{
if (Input.GetButton("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(shot, shotSpawn.position, shotSpawn.rotation);
}
}
八、边界设定
用来界定活动区域,子弹触碰到会消失,流星触碰到会消失,敌机触碰到会消失,不会过多占有内存。
1.创建cube命名为Boundary,覆盖画面,去掉材质网格(Mesh Renderer)会变成透明,勾选Collider触发(Is Trigger),添加脚本(DestoryByBoundary.cs)实现摧毁子弹功能。
(为什么会无效,注意OnTriggerExit的单词拼写)
(为什么消掉了子类VXF,却没有消掉父类bolt,因为把触碰器放在了子类,修改放在父类会解决问题)
using UnityEngine;
using System.Collections;
public class DestoryByBoundary : MonoBehaviour {
void OnTriggerExit(Collider other)
{//详细信息查询trigger有关的API
Destroy(other.gameObject);
}
}
九、旋转行星和摧毁行星
1.旋转功能,获取物体的角速度旋转angularVelocity,和随机insideUnitSphere让行星旋转。
2.创建空为Asteroid(重置),拖入行星,父类逻辑控制,子类纹理,增加Rigidbody,去掉重力,增加胶囊Collider,调整胶囊。
3.增加Mover脚本,给予负的速度。
4.增加RandomRotator脚本,使用钢体角速度的方法。
5.创建DestoryByContact.cs 脚本,利用OnTriggerEnter触碰方法摧毁接触物体,利用tag==“Boundary”来标记Boundary。
(会发生透明的情况,特别是立起来的时候,摄影机的位置要提高位置,物体出现在摄影机的后面导致部分透明无法显示)(怎么确定脚本放置的位置,根据脚本的目的)
RandomRotator.cs//行星的随机选择效果脚本
using UnityEngine;
using System.Collections;
public class RandomRotator : MonoBehaviour {
public float tumble;
void Start()
{
GetComponent<Rigidbody>().angularVelocity = Random.insideUnitSphere * tumble;
}
}
DestoryByContact.cs //销毁行星
using UnityEngine;
using System.Collections;
public class DestoryByContact : MonoBehaviour {
public GameObject explosion;
public GameObject playerExplosion;
void OnTriggerEnter(Collider other)
{
if (other.tag == "Boundary" || other.tag == "Enemy")
{
return;
}
if (explosion != null)
{
Instantiate(explosion, transform.position, transform.rotation);
}
if (other.tag == "Player")
{
Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
}
Destroy(other.gameObject); //摧毁与小行星碰撞的物体
Destroy(this.gameObject); //摧毁小行星
}
}