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 Colliderother 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.

刚体的角速度向量。

这里有关生成随机数的常用方法:

Random

  • 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。

时间: 2024-08-07 08:35:52

Unity初探—SpaceShoot的相关文章

Unity初探之黑暗之光(1)

Unity初探之黑暗之光(1) 1.镜头拉近 1 public float speed=10f;//镜头的移动速度 2 public int endZ = -20;//镜头的结束位置 3 4 // Update is called once per frame 5 void Update () { 6 if (transform.position.z<endZ) 7 { 8 transform.Translate(Vector3.forward * speed * Time.deltaTime)

unity初探之黑暗之光(2)

unity初探之黑暗之光(2) 一.设置角色跟随鼠标点击移动 思路:使用charactercollider的SimpleMove方法来控制角色的移动.通过摄像机的射线投射到地面,通过屏幕上的一个点也就是鼠标单击的点.该射线与地面发生碰撞返回发生碰撞的点,然后让角色转向该点,开始移动.当移动到一定范围时停止移动. 使用到的方法: Camera.ScreenPointToRay 屏幕位置转射线 function ScreenPointToRay (position : Vector3) : Ray

unity初探学习笔记-hello unity

unity3d是目前使用最广泛的3d游戏引擎之一,本系列教程将使用unity制作一款坦克大战游戏,从而带大家体验一下unity的使用. 这一篇教程主要介绍引擎的安装和环境的搭建,最后,我们会在手机上运行起来unity的第一个程序. 首先在unity的官方网站上下载unity的最新引擎,目前最新的版本是5.3.4,下载地址:http://unity3d.com/cn/get-unity/download?ref=personal 下载后一步步的按照提示安装即可,运行起unity,效果如下: 在这里

遗传算法初探-unity

遗传算法初探-unity unity 机器学习 MachineLearning 遗传算法 Genetic Algorithm 引子 :茫茫宇宙中存在着一个神级文明,尽管他们有着领先的科技,但文明的进程却因为种种因素逐步走向灭亡.为了防止自身文明的覆灭,神级文明想要通过模拟自身文明形成和发展来寻求解救自身的办法.于是他们用自己的科技创造了数以万计的小宇宙,并为其播种下生命起源的种子,让文明得以演化.他们为这些创造的世界中潜移默化的植入超越文明自身进化的技术,加速文明的进程.他们观测着这些文明的走向

Unity Shader 学习之旅-初探

Unity Shader 学习之旅-初探 unity shader 图形图像 美丽的梦和美丽的诗一样 都是可遇而不可求的--席慕蓉 最简单的顶点片元着色器 顶点片元着色器基本结构 Unity Shader基本结构:Shader ,Properties,SubShder,Fallback等. 结构 Shader "ShaderName"{  Properties{  //属性,暴露在inspector面板上  }  SubShader{  //针对显卡A的SubShader  Pass{

【Unity Shaders】初探Surface Shader背后的机制

转载请注明出处:http://blog.csdn.net/candycat1992/article/details/39994049 写在前面 一直以来,Unity Surface Shader背后的机制一直是刚開始学习的人为之困惑的地方. Unity Surface Shader在Unity 3.0的时候被开放给公众使用.其宣传手段也是号称让所有人都能够轻松地写shader.但因为资料缺乏,非常多人知其然不知其所以然,无法理解Unity Surface Shader在背后为我们做了哪些事情.

Unity 5 全局光照GI与新的烘焙系统初探

GI是啥 Realtime GI,实时全局光照,听上去就是一个非常高大上的词,但是越高大上就越令人心生敬畏,因为世上没有免费的午餐,越好的效果意味着越多的消耗,对于移动平台来说,这样的消耗受不受的起呢?首先来说说GI是干啥的,非常粗略的来描述下,如果说我们以前的光照系统就是由光源 - 物体 - 视点组成的话,那么全局光照系统就是由光源 - n多环境反射光 - 物体 - 视点.就是说GI额外包括了环境反射光的计算,它可以使得渲染出来的场景物体间的光影交互更为真实. 如果是离线烘焙的话,n多的环境反

Unity之UGUI初探—按钮动画

今天试了一下unity的新的UI系统—UGUI,感觉很强大,很多功能一目了然,使用起来相当方便接下来就是先试试使用他的动画吧 先创建一个UGUI的按钮,当然也可以先创建画布,然后在画布上创建按钮 然后点击按钮, 图中的transition的选项点开之后,有一项Animation的选项, 点击之后选择Auto Generate Animation 之后会弹出文件夹选项,就会意思是新建的这个动画的保存路径,自己选择路径命名即可,但要在Assets文件夹下 之后在window下,可以选择Animati

FingerGestures研究院之初探Unity手势操作

最近研究了一下Unity中的一个手势操作的插件FingerGestures.它能很方便监听到Unity中的各种手势事件:上下左右四方向的滑动事件.按下事件.抬起事件.移动事件.连击事件.长按事件等等.它同时支持触摸屏操作与鼠标操作,总起来说使用起来还是比较方便的,今天写下教程记录这个插件的详细使用步骤.首先下载这个插件,大家可以在圣典上找这个插件的下载地址,当然也可以在本文最后下载该插件.  我看了一下这个插件底层的实现步骤,他是通过C#代理的形式来实现手势操作的.如下图红圈内所示,这五个重要的