我觉得这个教程对我最大的启发就是其中的一句话, 子物体是贴图,父物体是属性。所以我们在创建物体前最好先建立一个空的gameobject,
这样既可以保持hierarchy面板整洁便于管理,又能实现刚才说的话。好了, 下面步入正题。
如何创建一个子弹?
我们先创建一个平面,然后将子弹的贴图赋给这个平面,然后再将shader选项选中mobile的particles的additive,这样就只有激光那部分可以显示出来,
黑色部分就会小时,最后在给子弹添加rigidbody组件和capsule Collider组件,这样子弹就完成了。
如何让子弹前进?
直接在子弹z轴方向给一个初速度就好了
using UnityEngine;
using System.Collections;
public class BoltMove : MonoBehaviour {
public float speed;
// Use this for initialization
void Start () {
rigidbody.velocity = transform.forward * speed;
}
}
如何让子弹按一定频率发射?
void Update(){
//在固定的时间段生成一个物体
if (Time.time > nextFire) {
nextFire = Time.time + fireRate;
Instantiate (shot, shotSpawn.position, shotSpawn.rotation);
}
}
shotSpwan.position是飞船的位置,fireRate就是我们想要的频率
如何将飞船的移动限制在一定范围?
这里我们需要用到一个函数mathf中的Clamp
using UnityEngine;
using System.Collections;
[System.Serializable]
public class Limit{
public float xMax,xMin,zMax,zMin;
}
public class PlayrControl : MonoBehaviour {
public float speed;
public Limit limit;
public float tilt;
public GameObject shot;
public Transform shotSpawn;
void FixedUpdate(){
float x = Input.GetAxis ("Horizontal");
float y = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (x, 0.0f, y);
rigidbody.velocity = movement * speed;
rigidbody.position = new Vector3
(
Mathf.Clamp(rigidbody.position.x, limit.xMin, limit.xMax),
0.0f,
Mathf.Clamp(rigidbody.position.z, limit.zMin, limit.zMax)
);
rigidbody.rotation = Quaternion.Euler (0.0f, 0.0f, rigidbody.velocity.x * -tilt);
}
}
当子弹和陨石飞出边界时如何销毁?
这里我们需要一个大的Cube将我们游戏场景围起来,然后给Cube添加一个Box Collider组件,然后检测如果有物体离开触发器,销毁就好了
void OnTriggerExit(Collider other) {
Destroy(other.gameObject);
}
子弹与陨石碰撞或者飞船与陨石碰撞,如何同时销毁且产生爆炸效果?
void OnTriggerEnter(Collider other) {
if (other.tag == "Boundary")
return;
hard++;
if (hard == 2) {
Instantiate (explosion, other.transform.position, other.transform.rotation);
Destroy (gameObject);
gameControl.AddScore(scoreValue);
}
if (other.tag == "Player") {
Instantiate (player_explosion, other.transform.position, other.transform.rotation);
Destroy (gameObject);
gameControl.gameOver = true;
}
//Debug.Log (other.name);
Destroy(other.gameObject);
}
我解释一下,
if (other.tag == "Boundary")
因为这个函数是当进入触发器时执行,但是我们的陨石一直在Cube的触发器中, 所以我们要排除Cube的干扰
Instantiate (explosion, other.transform.position, other.transform.rotation);
这句话就是在子弹当前位置产生一个爆炸效果物体
如何一波一波的生成敌人?
void Start(){
StartCoroutine(SpawnWaves ());
}
IEnumerator SpawnWaves(){
while (true) {
yield return new WaitForSeconds (startWait);
for (int i = 0; i < hazardCount; i++) {
Vector3 spawnPositoin = new Vector3 (Random.Range (-spawnValues.x - 3, spawnValues.x - 3), 0, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate (hazard, spawnPositoin, spawnRotation);
yield return new WaitForSeconds (spawnWait);
}
}
}
推荐一个公众号,不吐槽,不毒舌,偶尔发发文章,偶尔推荐好物,欢迎关注或者有女票的程序狗们推荐给女票