陨石移动分为直线运动和旋转
因为子弹的发射也是直线运动,所以直线运动和旋转分开,写两个脚本,子弹和陨石的直线运动公用一个脚本。
角速度脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AngleRate : MonoBehaviour {
Rigidbody rd;
public float Mulity=10;
// Use this for initialization
void Start () {
rd = this.GetComponent<Rigidbody>();
rd.angularVelocity = Random.insideUnitSphere * Mulity;//一个随机的初始的角速度
}
// Update is called once per frame
void Update () {
//如果角速度写在这里,就会出现不停变换角速度的情况——摇摇晃晃的运动而不是滚动
}
}
直线运动脚本
注意陨石是从上往下直线运动,所以在陨石的Inspector面板中要将speed赋负值。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move: MonoBehaviour {
Rigidbody rd;
public float speed= 10f;
void Start () {
rd = this.GetComponent<Rigidbody>();
rd.velocity = transform.forward*speed;//向前运动
}
}
陨石子弹回收脚本
未被子弹击中的陨石和没有击中陨石的子弹,不能让它们一直存活着。创建一个cube,大小与背景相符,取消它的渲染(Mesh Filter和Mesh Render),留下刚体rigidbody和盒子碰撞器Box Collider。设置当物体与cube碰撞销毁该物体。销毁的脚本如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Destroy : MonoBehaviour {
private void OnTriggerExit(Collider other)
{
Destroy(other.gameObject);
}
}
这个脚本是添加在cube上的,碰到cube的物体销毁。做的时候为了观察触发器的触发时间所以用了OnTriggerExit方法,逻辑上用OnTriggerEnter比较合适。不过在这个项目里面没什么,我也就没有改了。
击中销毁脚本
GameController 是控制游戏流程的脚本。在另外一篇博客中会写到。
这段代码涉及到的碰撞有两种,陨石撞到子弹、陨石撞到飞机。
陨石撞到飞机游戏结束。所以调用了GameOver方法。
同样的,这里两个爆炸效果设置为public,从unity那边直接拖拉赋值引用。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyByCollision : MonoBehaviour {
public GameObject asExprosion;
public GameObject plExprosion;
private GameController gameController;
public int perScore=10;
private void Start()
{
GameObject gameObject = GameObject.FindWithTag("GameController");
if (gameObject != null)
{
gameController = gameObject.GetComponent<GameController>();
}
if (gameController == null)
Debug.Log("gameController==null");
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Boundary")
{
return;//这是判断如果碰到的是边界就不进行操作
}
if (other.gameObject.tag == "Player")
{//撞到飞机
Instantiate(plExprosion, other.transform.position, other.transform.rotation);//实例化一个飞机爆炸效果
gameController.GameOver();
}
Destroy(other.gameObject);
gameController.AddScore(perScore);//击中陨石,加分
Destroy(this.gameObject);
Instantiate(asExprosion, transform.position, transform.rotation);
//实例化一个陨石爆炸效果
}
}
爆炸效果的回收
上面一个脚本实例化的爆炸效果,如果没有回收的话会一直停留在原地,尽管我们看不见。所以还要写一个回收爆炸效果的脚本。只要生命周期到了就销毁,爆炸效果本身是素材,Inspector面板中可以设置生存周期。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyExplosion : MonoBehaviour {
// Use this for initialization
public int life;
void Start () {
}
// Update is called once per frame
void Update () {
Destroy(this.gameObject, life);
}
}