Unity初探—SpaceShoot


DestroyByBoundary脚本(C#)

  在游戏中我们添加了一个Cube正方体,让他来作为游戏的边界。它是可以触发触发事件的(勾选Is Trigger),当游戏中的碰撞体结束trigger事件,也就是出了正方体边界,我们就将其销毁。

 void OnTriggerExit(Collider other)
{
Destroy(other.gameObject);
}

Description描述

OnTriggerExit is called when the Colliderother has stopped touching the trigger .

当Collider(碰撞体)停止触发trigger(触发器)时调用OnTriggerExit。


Mover脚本

  游戏中通过该脚本来控制陨石的坠落和子弹的射出,他们都是在Z轴方向上运动。通过设置speed可以控制其飞行的速度和前后方向。

 public float speed;
// Use this for initialization
void Start () {
GetComponent<Rigidbody>().velocity = transform.forward * speed;
}

Description描述

The velocity vector of the rigidbody.

刚体的速度向量。

这里有各个轴的定义:

transform.forward:蓝色Z轴
transform.right:红色轴X轴
transform.up:黄色轴Y轴。

RandomRotator脚本

  游戏中的陨石在飞行的过程中我们希望让他翻滚掉了,这里我们为他添加了翻滚的脚本。其中tumble用来控制滚动速度。

 public float tumble;//gun dong
// Use this for initialization
void Start () {
GetComponent<Rigidbody>().angularVelocity = Random.insideUnitSphere * tumble;
}
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脚本

  该脚本用来控制飞船的飞翔范围,倾斜角,射击速度等。

 using UnityEngine;
using System.Collections; [System.Serializable]
public class Boundary
{
public float xMin, xMax, zMin, zMax;
}
public class PlayerController : MonoBehaviour
{
public float speed;
public float tilt;
public Boundary boundary; private float nextFire;
public float fireRate;
public GameObject shot;
public Transform shotSqawn;
// Use this for initialization
void Start()
{ } // Update is called once per frame
void Update()
{
if (Input.GetButton("Fire1")&&Time.time >nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(shot, shotSqawn.position, shotSqawn.rotation);
GetComponent<AudioSource>().Play();
}
} void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical"); Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
GetComponent<Rigidbody>().velocity = movement * speed;
GetComponent<Rigidbody>().rotation = Quaternion.Euler(0.0f, 0.0f, GetComponent<Rigidbody>().velocity.x * -tilt); GetComponent<Rigidbody>().position = new Vector3(
Mathf.Clamp(GetComponent<Rigidbody>().position.x,boundary.xMin,boundary.xMax),
0.0f,
Mathf.Clamp(GetComponent<Rigidbody>().position.z, boundary.zMin, boundary.zMax)
);
}
}

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 对象。

 public GameObject explosion;
public GameObject playerExplosion;
public int score;
private GameController gameController; void Start()
{
GameObject gameControllerObject = GameObject.FindWithTag("GameController");
if (gameControllerObject!=null)
{
gameController = gameControllerObject.GetComponent<GameController>();
}
if (gameControllerObject == null)
{
Debug.Log("Can't fing 'GameController' script");
}
}
void OnTriggerEnter(Collider other)
{
if (other.tag=="Boundary")
{
return;
}
if (other.tag=="PlayerL")
{
Instantiate(playerExplosion ,other.transform.position,other.transform.rotation);
gameController.GameOver();
}
gameController.addScore(score);
Instantiate(explosion,transform.position,transform.rotation);
Destroy(other.gameObject);
Destroy(gameObject);
}

DestroyByTime脚本

  创建脚本,使得一些游戏对象可以在一定的时间后销毁。

     public float lifeTime;
// Use this for initialization
void Start () {
Destroy(gameObject, lifeTime);
}

GameController脚本

  创建GameController脚本来控制游戏的核心逻辑,包括游戏中陨石障碍物的掉落,游戏结束控制,游戏重开控制,分数统计等。

 using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement; public class GameController : MonoBehaviour { public GameObject hazard;
public Vector3 spawnValue;
public int hazardCount;
public float spawnWait;
public float starWait;
public float waveWait; private int score;
public Text scoreText; public Text gameOverText;
private bool gameOver; public Text restartText;
public bool restart;
// Use this for initialization
void Start () {
gameOverText.text = "";
gameOver = false; restartText.text = "";
restart = false; score = ;
UpdateScore();
StartCoroutine( SpawnWave());
} void Update()
{
if (restart)
{
if (Input.GetKeyDown(KeyCode.R))
{
//Application.LoadLevel(Application.loadedLevel);
SceneManager.LoadScene("Mytest");
} }
}
IEnumerator SpawnWave()
{
while (true)
{
yield return new WaitForSeconds(starWait);
for (int i = ; i < hazardCount; i++)
{
Vector3 spawnPosition = new Vector3(Random.Range(-spawnValue.x, spawnValue.x),
spawnValue.y,
spawnValue.z);
Quaternion spawRotation = Quaternion.identity;
Instantiate(hazard, spawnPosition, spawRotation);
yield return new WaitForSeconds(spawnWait); if (gameOver)
{
restart = true;
restartText.text = "Press 'R' to Restart";
}
}
yield return new WaitForSeconds(waveWait);
}
} public void GameOver()
{
gameOver = true;
gameOverText.text = "GameOver";
} void UpdateScore()
{
scoreText.text = "Score: " + score;
}
public void addScore(int value)
{
score += value;
UpdateScore();
}
}

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。

Unity初探—SpaceShoot的更多相关文章

  1. unity初探之黑暗之光(2)

    unity初探之黑暗之光(2) 一.设置角色跟随鼠标点击移动 思路:使用charactercollider的SimpleMove方法来控制角色的移动.通过摄像机的射线投射到地面,通过屏幕上的一个点也就 ...

  2. Unity初探之黑暗之光(1)

    Unity初探之黑暗之光(1) 1.镜头拉近 public float speed=10f;//镜头的移动速度 ;//镜头的结束位置 // Update is called once per fram ...

  3. 基于Unity的AR开发初探:第一个AR应用程序

    记得2014年曾经写过一个Unity3D的游戏开发初探系列,收获了很多好评和鼓励,不过自那之后再也没有用过Unity,因为没有相关的需求让我能用到.目前公司有一个App开发的需求,想要融合一下AR到A ...

  4. 在Unity中使用TDD - 初探

    描述 Editor Tests Runner是Unity中用来实现TDD的,其内部实现是基于NUnit. 其他 测试脚本要放在Editor文件夹中,测试要能够在一帧的时间内完成. 使用 打开Edito ...

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

    转载请注明出处:http://blog.csdn.net/candycat1992/article/details/39994049 写在前面 一直以来,Unity Surface Shader背后的 ...

  6. 基于Unity的AR开发初探:发布AR应用到Android平台

    本文接上一篇,介绍一下如何通过Unity发布第一个AR应用至Android平台,在Android手机上使用我们的第一个AR应用. 一.一些准备工作 1.1 准备Java JDK 这里选择的是JDK 1 ...

  7. Unity ECS 初探

    1.安装 安装两个包 2.初探 实例化 注:实例化的实体并不会在Hierarchy视图里面显示,可在EntityDebugger窗口里面显示,因此需要显示的话需要添加Rendermeshcompone ...

  8. Unity的RuntimeInitializeOnLoadMethod属性初探

    Unity 5.0开始增加了RuntimeInitializeOnLoadMethodAttribute,这样就很方便在游戏初始化之前做一些额外的初始化工作,比如:Bulgy参数设置.SDK初始等工作 ...

  9. Unity 摄像机旋转初探

    接触打飞机的游戏时都会碰见把摄像机绕 x 轴顺时针旋转 90°形成俯瞰的视角的去看飞船.也没有多想,就感觉是坐标系绕 x 轴旋转 90°完事了.但是昨天用手比划发一下发现不对.我就想这样的话绕 x 轴 ...

随机推荐

  1. Qgis 里的Python脚本介绍

    QGIS 入门演示之<用 QGIS 画矢量交通路线图> 脚本编程之准备知识<Python 教程> QGIS API QGIS插件库 运行QGIS脚本,对于桌面应用来讲有4种方式 ...

  2. idea中ssm自动配置

    自动生成 只需要创建好maven项目,然后创建一个类Test,复制代码粘贴即可 使用注意: 代码 import java.io.*; public class Test { //包名格式 //列如配置 ...

  3. PAT——1017. A除以B

    本题要求计算A/B,其中A是不超过1000位的正整数,B是1位正整数.你需要输出商数Q和余数R,使得A = B * Q + R成立. 输入格式: 输入在1行中依次给出A和B,中间以1空格分隔. 输出格 ...

  4. UITableView控件didSelectRow和didDeselectRow方法注意事项

    UITableView控件didSelectRow和didDeselectRow方法注意事项 1. 因Xcode强大的自动补全功能,在使用UITableView如下两个方法时,务必特别小心,避免出错: ...

  5. 安全过滤javascript,html,防止跨脚本攻击

    本文改自: http://blog.51yip.com/php/1031.html 用户输入的东西是不可信认的,例如,用户注册,用户评论等,这样的数据,你不光要做好防sql的注入,还要防止JS的注入, ...

  6. java判断类型

    判断是否String:str.getClass().getName().equals("java.lang.String") 判断是否在且不为空:Object.hasKey(&qu ...

  7. 2018 CVTE 前端校招笔试题整理

    昨天晚上(7.20)做了CVTE的前端笔试,总共三十道题,28道多选题,2道编程题 .做完了之后觉得自己基础还是不够扎实,故在此整理出答案,让自己能从中得到收获,同时给日后的同学一些参考. 首先说一下 ...

  8. 学生管理系统增删查基本操作(dom4j/sax技术)

    基本代码: student.xml <?xml version="1.0" encoding="UTF-8"?><student> &l ...

  9. js实现所有异步请求全部加载完毕后,loading效果消失

    在实际开发中,一定有情况是这样的,一个页面我们有多个地方请求了ajax,在这种情况下,我们要实现数据没来之前出现我们炫酷的loading效果,而且要等到所有的ajax都请求完毕后,才让我们的loadi ...

  10. Web移动端商城 移动端商城手机网站html整套模板,web移动商城仿app手机模板下载

    --Web移动端商城移动端商城手机网站html整套模板,web移动商城仿app手机模板下载.原生的js和jquery-1.6.2.min.js,页面才有html5自适应.包括首页(轮播,导航).兼职( ...