Unity初探—SpaceShoot
Unity初探—SpaceShoot
DestroyByBoundary脚本(C#)
在游戏中我们添加了一个Cube正方体,让他来作为游戏的边界。它是可以触发触发事件的(勾选Is Trigger),当游戏中的碰撞体结束trigger事件,也就是出了正方体边界,我们就将其销毁。
1 void OnTriggerExit(Collider other) 2 { 3 Destroy(other.gameObject); 4 }
Description描述
OnTriggerExit is called when the Collider other has stopped touching the trigger .
当Collider(碰撞体)停止触发trigger(触发器)时调用OnTriggerExit。
Mover脚本
游戏中通过该脚本来控制陨石的坠落和子弹的射出,他们都是在Z轴方向上运动。通过设置speed可以控制其飞行的速度和前后方向。
1 public float speed; 2 // Use this for initialization 3 void Start () { 4 GetComponent<Rigidbody>().velocity = transform.forward * speed; 5 }
Description描述
The velocity vector of the rigidbody.
刚体的速度向量。
这里有各个轴的定义:
transform.forward:蓝色Z轴
transform.right:红色轴X轴
transform.up:黄色轴Y轴。
RandomRotator脚本
游戏中的陨石在飞行的过程中我们希望让他翻滚掉了,这里我们为他添加了翻滚的脚本。其中tumble用来控制滚动速度。
1 public float tumble;//gun dong 2 // Use this for initialization 3 void Start () { 4 GetComponent<Rigidbody>().angularVelocity = Random.insideUnitSphere * tumble; 5 }
Rigidbody.angularVelocity
Description描述
The angular velocity vector of the rigidbody.
刚体的角速度向量。
这里有关生成随机数的常用方法:
- insideUnitCircle:返回单位半径为1圆中随机一点。
- insideUnitSphere:返回单位半径为1球体中随机一点。
- onUnitSphere:返回单位半径为1球体表面上随机一点。
- Range:Min~Max
- rotation:返回一个随机的角度(只读)。
- seed:设置用于生成随机数的种子
- value:返回[0.0~1.0] 之间的随机数(只读)
PlayerController脚本
该脚本用来控制飞船的飞翔范围,倾斜角,射击速度等。
1 using UnityEngine; 2 using System.Collections; 3 4 [System.Serializable] 5 public class Boundary 6 { 7 public float xMin, xMax, zMin, zMax; 8 } 9 public class PlayerController : MonoBehaviour 10 { 11 public float speed; 12 public float tilt; 13 public Boundary boundary; 14 15 private float nextFire; 16 public float fireRate; 17 public GameObject shot; 18 public Transform shotSqawn; 19 // Use this for initialization 20 void Start() 21 { 22 23 } 24 25 // Update is called once per frame 26 void Update() 27 { 28 if (Input.GetButton("Fire1")&&Time.time >nextFire) 29 { 30 nextFire = Time.time + fireRate; 31 Instantiate(shot, shotSqawn.position, shotSqawn.rotation); 32 GetComponent<AudioSource>().Play(); 33 } 34 } 35 36 void FixedUpdate() 37 { 38 float moveHorizontal = Input.GetAxis("Horizontal"); 39 float moveVertical = Input.GetAxis("Vertical"); 40 41 Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical); 42 GetComponent<Rigidbody>().velocity = movement * speed; 43 GetComponent<Rigidbody>().rotation = Quaternion.Euler(0.0f, 0.0f, GetComponent<Rigidbody>().velocity.x * -tilt); 44 45 GetComponent<Rigidbody>().position = new Vector3( 46 Mathf.Clamp(GetComponent<Rigidbody>().position.x,boundary.xMin,boundary.xMax), 47 0.0f, 48 Mathf.Clamp(GetComponent<Rigidbody>().position.z, boundary.zMin, boundary.zMax) 49 ); 50 } 51 }
Serializable 序列化:
Inherits from Attribute
The Serializable attribute lets you embed a class with sub properties in the inspector.
Serializable(序列化)属性让你植入一个类用替代内容在Inspector(检视面板)
------------------------------------------------------------------------------------------------------
Mathf.Clamp 限制
static function Clamp (value : float, min : float, max : float) : float
Description描述
Clamps a value between a minimum float and maximum float value.
限制value的值在min和max之间, 如果value小于min,返回min。 如果value大于max,返回max,否则返回value
------------------------------------------------------------------------------------------------------
Time.deltaTime 增量时间
static var deltaTime : float
Description描述
The time in seconds it took to complete the last frame (Read Only).
以秒计算,完成最后一帧的时间(只读)。
Use this function to make your game frame rate independent.
使用这个函数使和你的游戏帧速率无关。
放在Update()函数中的代码是以帧来执行的.如果我们需要物体的移动以秒来执行.我们需要将物体移动的值乘以Time.deltaTime。
------------------------------------------------------------------------------------------------------
Quaternion.Euler 欧拉角
static function Euler (x : float, y : float, z : float) : Quaternion
Description描述
Returns a rotation that rotates z degrees around the z axis, x degrees around the x axis, and y degrees around the y axis (in that order).
返回一个旋转角度,绕z轴旋转z度,绕x轴旋转x度,绕y轴旋转y度(像这样的顺序)。
------------------------------------------------------------------------------------------------------
DestroyByContact脚本
该脚本控制游戏中一些对象的销毁工作,playerExplosion为飞船爆炸时触发的特效,score为积分,gameController为GameController 对象。
1 public GameObject explosion; 2 public GameObject playerExplosion; 3 public int score; 4 private GameController gameController; 5 6 void Start() 7 { 8 GameObject gameControllerObject = GameObject.FindWithTag("GameController"); 9 if (gameControllerObject!=null) 10 { 11 gameController = gameControllerObject.GetComponent<GameController>(); 12 } 13 if (gameControllerObject == null) 14 { 15 Debug.Log("Can't fing 'GameController' script"); 16 } 17 } 18 void OnTriggerEnter(Collider other) 19 { 20 if (other.tag=="Boundary") 21 { 22 return; 23 } 24 if (other.tag=="PlayerL") 25 { 26 Instantiate(playerExplosion ,other.transform.position,other.transform.rotation); 27 gameController.GameOver(); 28 } 29 gameController.addScore(score); 30 Instantiate(explosion,transform.position,transform.rotation); 31 Destroy(other.gameObject); 32 Destroy(gameObject); 33 }
DestroyByTime脚本
创建脚本,使得一些游戏对象可以在一定的时间后销毁。
1 public float lifeTime; 2 // Use this for initialization 3 void Start () { 4 Destroy(gameObject, lifeTime); 5 }
GameController脚本
创建GameController脚本来控制游戏的核心逻辑,包括游戏中陨石障碍物的掉落,游戏结束控制,游戏重开控制,分数统计等。
1 using UnityEngine; 2 using System.Collections; 3 using UnityEngine.UI; 4 using UnityEngine.SceneManagement; 5 6 public class GameController : MonoBehaviour { 7 8 public GameObject hazard; 9 public Vector3 spawnValue; 10 public int hazardCount; 11 public float spawnWait; 12 public float starWait; 13 public float waveWait; 14 15 private int score; 16 public Text scoreText; 17 18 public Text gameOverText; 19 private bool gameOver; 20 21 public Text restartText; 22 public bool restart; 23 // Use this for initialization 24 void Start () { 25 gameOverText.text = ""; 26 gameOver = false; 27 28 restartText.text = ""; 29 restart = false; 30 31 score = 0; 32 UpdateScore(); 33 StartCoroutine( SpawnWave()); 34 } 35 36 void Update() 37 { 38 if (restart) 39 { 40 if (Input.GetKeyDown(KeyCode.R)) 41 { 42 //Application.LoadLevel(Application.loadedLevel); 43 SceneManager.LoadScene("Mytest"); 44 } 45 46 } 47 } 48 IEnumerator SpawnWave() 49 { 50 while (true) 51 { 52 yield return new WaitForSeconds(starWait); 53 for (int i = 0; i < hazardCount; i++) 54 { 55 Vector3 spawnPosition = new Vector3(Random.Range(-spawnValue.x, spawnValue.x), 56 spawnValue.y, 57 spawnValue.z); 58 Quaternion spawRotation = Quaternion.identity; 59 Instantiate(hazard, spawnPosition, spawRotation); 60 yield return new WaitForSeconds(spawnWait); 61 62 if (gameOver) 63 { 64 restart = true; 65 restartText.text = "Press 'R' to Restart"; 66 } 67 } 68 yield return new WaitForSeconds(waveWait); 69 } 70 } 71 72 public void GameOver() 73 { 74 gameOver = true; 75 gameOverText.text = "GameOver"; 76 } 77 78 void UpdateScore() 79 { 80 scoreText.text = "Score: " + score; 81 } 82 public void addScore(int value) 83 { 84 score += value; 85 UpdateScore(); 86 } 87 }
MonoBehaviour.StartCoroutine 开始协同程序
function StartCoroutine (routine : IEnumerator) : Coroutine
Description描述
Starts a coroutine.
开始协同程序。
The execution of a coroutine can be paused at any point using the yield statement. The yield return value specifies when the coroutine is resumed. Coroutines are excellent when modelling behaviour over several frames. Coroutines have virtually no performance overhead. StartCoroutine function always returns immediately, however you can yield the result. This will wait until the coroutine has finished execution.
一个协同程序在执行过程中,可以在任意位置使用yield语句。yield的返回值控制何时恢复协同程序向下执行。协同程序在对象自有帧执行过程中堪称优秀。协同程序在性能上没有更多的开销。StartCoroutine函数是立刻返回的,但是yield可以延迟结果。直到协同程序执行完毕。
When using JavaScript it is not necessary to use StartCoroutine, the compiler will do this for you. When writing C# code you must call StartCoroutine.
用javascript不需要添加StartCoroutine,编译器将会替你完成.但是在C#下,你必须调用StartCoroutine。
作者:世纪末的魔术师
出处:https://www.cnblogs.com/Firepad-magic/
Unity最受欢迎插件推荐:点击查看
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。