主要框架视图
关键代码
FireWall
public class FireWall : MonoBehaviour {
//火向前推进速度
public float creepSpeed = 0.01f;
//主角引用
private Player player;
//判断游戏状态
private LevelState state;
void Start () {
player = GameObject.FindObjectOfType<Player>();
state = GameObject.FindObjectOfType<LevelState>();
}
void Update () {
//游戏没结束
if (!state.isGameOver)
{
FollowPlayer();
CreepFoward();
CheckPlayerBurnt();
}
}
void FollowPlayer() {
//让火跟随玩家
GameObject player = GameObject.Find("Player");
Vector3 delta = player.transform.position - transform.position;
Vector3 projectedDelta = Vector3.Project(delta, Vector3.left);
transform.position += projectedDelta;
}
//向前推进速度;
void CreepFoward() {
transform.position += Vector3.forward * creepSpeed;
}
/// <summary>
/// 检查玩家是否受伤害
/// </summary>
void CheckPlayerBurnt() {
if (player.transform.position.z<transform.position.z)
{
state.isGameOver = true;
}
}
}
FireDestroyer
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FireDestroyer : MonoBehaviour {
/// <summary>
/// 销毁车道
/// </summary>
/// <param name="collider"></param>
private void OnTriggerEnter(Collider collider)
{
//把碰到的车道销毁掉
Destroy(collider.gameObject);
}
}
GameOverMessage
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameOverMessage : MonoBehaviour {
//UI距离
public float UIDistance = 5.0f;
public float UIHeight = 2.0f;
//获取主角的引用
private Player player;
//结束UI
private Canvas canvas;
//游戏状态
private LevelState state;
void Start () {
player = GameObject.FindObjectOfType<Player>();
canvas = GetComponent<Canvas>();
//画面一开始不可用
canvas.enabled = false;
state = GameObject.FindObjectOfType<LevelState>();
}
void Update () {
//判断是否游戏结束
if (state.isGameOver)
{
TrackPlayerHead();
canvas.enabled = true;
}
}
/// <summary>
/// 追踪主角头部
/// </summary>
void TrackPlayerHead() {
//结束UI画面跟随主角
//旋转
transform.rotation = Quaternion.LookRotation(player.LookDirection());
//位置
transform.position = player.transform.position;
transform.position += player.LookDirection() * UIDistance;
transform.position += Vector3.up * UIHeight;
}
}
GameState
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameState : MonoBehaviour {
//分数引用
public int hightScore;
/// <summary>
/// 加载时不要销毁gamestate 三个场景共用
/// </summary>
private void Awake()
{
DontDestroyOnLoad(gameObject);
}
/// <summary>
/// 更新分数的方法
/// </summary>
public void UpdateHightScore(int newScore)
{
hightScore = newScore;
}
}
HightScore
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HightScore : MonoBehaviour {
void Start () {
//获取分数
GameState state = GameObject.FindObjectOfType<GameState>();
Text text = GetComponent<Text>();
text.text ="High Score: "+ state.hightScore+" Meters";
}
}
LethalCollider
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//此脚本挂在车上
public class LethalCollider : MonoBehaviour {
/// <summary>
/// 车碰到玩家及游戏结束
/// </summary>
/// <param name="collision"></param>
private void OnCollisionEnter(Collision collision)
{
//获取玩家
Player player = collision.gameObject.GetComponent<Player>();
//判断玩家是否为空
if (player !=null)
{
LevelState state = GameObject.FindObjectOfType<LevelState>();
state.isGameOver = true;
}
}
}
LevelState
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelState : MonoBehaviour {
//判断游戏是否结束的字段
public bool _isGameOver = false;
//判断游戏是否结束属性
public bool isGameOver{
get { return _isGameOver; }
set {
if (value)
{
SetHightScore();
}
_isGameOver = true;
}
}
/// <summary>
/// 设置分数
/// </summary>
void SetHightScore() {
GameState state = GameObject.FindObjectOfType<GameState>();
Player player = GameObject.FindObjectOfType<Player>();
//数学公式 将位置转成数值
int score = Mathf.FloorToInt(player.transform.position.z);
state.UpdateHightScore(score);
}
//重新开始游戏
public void ResetGame() {
//SceneManager.LoadScene("Main");
//重构代码
ScenesLoder loader = GameObject.FindObjectOfType<ScenesLoder>();
loader.LoadLevelByOffset(0);
}
//返回游戏
public void BackGame(){
// SceneManager.LoadScene("SphashScreen");
//重构代码
ScenesLoder loader = GameObject.FindObjectOfType<ScenesLoder>();
loader.LoadLevelByOffset(-1);
}
}
Player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Player : MonoBehaviour {
//获取视选引用
private CardboardHead Head;
//声明一个公开的变量 吧UI拖进去
// public Text GazeText;
//添加刚体
private Rigidbody rigi;
//引用角速度和速度
public float jumpAngleIndegree=32f;
public float jumpSpeed=3f;
//检查是否碰撞到地面
private bool onFloor;
//最后一跳时间
private float lastJumpRequestTime = 0f;
//获取游戏状态
private LevelState state;
void Start()
{
//触发事件
Cardboard.SDK.OnTrigger += PullTrigger;
//获取引用
Head = GameObject.FindObjectOfType<CardboardHead>();
//获取rigi组件
rigi = GetComponent<Rigidbody>();
state = GameObject.FindObjectOfType<LevelState>();
}
void Update()
{
//在UI上打印视选值;
// GazeText.text = GazePrintHead.Gaze.ToString();
}
/// <summary>
/// 触发事件后的行为 盒子上的小弹片 点击事件
/// </summary>
void PullTrigger()
{
//打印测试
// print("Pull The Trigger!!!");
//视选文本取反 点击隐藏或显示
//GazeText.enabled = !GazeText.enabled;
//在头部凝视方向添加一个向前的力
// rigi.AddForce(Head.Gaze.direction*1000);
//改成速率
// rigi.velocity = Head.Gaze.direction * 10;
//是否在地面
//if (onFloor)
//{
//}
RequestJump();
}
//请求是够可以眺
private void RequestJump() {
lastJumpRequestTime = Time.time;
rigi.WakeUp();
}
//起跳
private void Jump() {
//判断游戏不是结束状态才可以眺,结束不能跳;
if (!state.isGameOver)
{
//Jump
//度转弧度
float jumpAngleInRadins = jumpAngleIndegree * Mathf.Deg2Rad;
// Vector3 projectedVector = Vector3.ProjectOnPlane(Head.Gaze.direction, Vector3.up);
// Vector3 jumpVector = Vector3.RotateTowards(projectedVector, Vector3.up, jumpAngleInRadins, 0);
Vector3 jumpVector = Vector3.RotateTowards(LookDirection(), Vector3.up, jumpAngleInRadins, 0);
rigi.velocity = jumpVector * jumpSpeed;
}
}
public Vector3 LookDirection() {
return Vector3.ProjectOnPlane(Head.Gaze.direction, Vector3.up);
}
//检测是否碰撞到地面 避免在空中连续跳
//private void OnCollisionEnter(Collision collision)
//{
// onFloor = true;
//}
//private void OnCollisionExit(Collision collision)
//{
// onFloor = false;
//}
/// <summary>
/// 当碰到物体时,判断起跳时间
/// </summary>
/// <param name="collision"></param>
private void OnCollisionStay(Collision collision)
{
float delta = Time.time - lastJumpRequestTime;
if (delta<0.1f)
{
Jump();
lastJumpRequestTime = 0f;
}
}
}
ScenesLoder
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ScenesLoder : MonoBehaviour {
//延迟调用时间 开始启动
public float loadLevelAfterTime = 0;
void Start () {
//判断时间大于零的话 调用场景
if (loadLevelAfterTime>0)
{
Invoke("LoadNextLevel", loadLevelAfterTime);
}
}
//调用场景的方法
public void LoadNextLevel() {
//调用指定场景
// SceneManager.LoadScene("Login");
//当前场景直接调转下一场景
// SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex+1);
LoadLevelByOffset(1);
}
//迭代
public void LoadLevelByOffset(int indexOffset) {
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + indexOffset);
}
}
Spawner
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour {
//随机生成有草马路或者普通马路
public GameObject[] lanePrefabs;
//生成的马路长度
public float spawnHorizon = 500f;
//车道的宽度
public float laneWidth = 2f;
//主角
public GameObject player;
//父类;
public Transform spwanerParent;
//偏移
private float nextLaneOffset = 0f;
void Start () {
}
void Update () {
//主角的位置
float forwardPosition = player.transform.position.z;
//判断主角位置+长度大于偏移位置 实例化物体
while (forwardPosition+spawnHorizon>nextLaneOffset)
{
//随机马路形式的范围
int randomLaneIndex = Random.Range(0,lanePrefabs.Length);
//随机的预制体
GameObject lane = lanePrefabs[randomLaneIndex];
//定义下一个马路的位置
Vector3 nextLanePosition = nextLaneOffset * Vector3.forward;
//实例化马路
GameObject newLane= Instantiate(lane,nextLanePosition,Quaternion.identity) as GameObject;
//父类
newLane.transform.parent = spwanerParent;
//偏移量
nextLaneOffset += laneWidth;
}
}
}
Vehicle
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//此脚本挂在车上
public class Vehicle : MonoBehaviour {
//定义速度
private float speed=5.0f;
//定义销毁长度
// private float lifeTime = 10f;
private float length = 20f;
void Start () {
//函数调用 10秒过后移除车辆
// Invoke("RemoveVehicle",lifeTime);
float lifeTime = length / speed;
Invoke("RemoveVehicle",lifeTime);
}
void Update () {
//车跑起来了
transform.position += Vector3.right * speed * Time.deltaTime;
}
//速度可改变
public void SetPath(float someSpeed,float someLifeTime) {
speed = someSpeed;
length = someLifeTime;
}
/// <summary>
///移除车辆
/// </summary>
public void RemoveVehicle() {
Destroy(gameObject);
}
}
VehicleSpanwer
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VehicleSpanwer : MonoBehaviour {
//此脚本挂在预制体道路上
//定义公开的车辆
public GameObject[] vehiclePrefabs;
//高度
public float heightOffset = 1f;
//开始位置
public float StartOffset = -20f;
//速度
public float Speed=5.0f;
//车辆销毁时间
// public float LifeTime = 2f;
public float length = 20f;
//生成车辆时间
public float maxSpwanTime=5f;
void Start() {
//test
//Instantiate(vehiclePrefabs[0],transform.position,transform.rotation);
// InstantiateVehicle();
//开启协程
StartCoroutine("Spawn");
}
/// <summary>
/// 实例化车辆
/// </summary>
public void InstantiateVehicle(int vehicleIndex) {
GameObject vehicleObject = Instantiate(vehiclePrefabs[vehicleIndex]) ;
vehicleObject.transform.position = GetPositionOffset();
vehicleObject.transform.parent = transform;
//获取车辆
Vehicle vehicleComponent =vehicleObject.GetComponent<Vehicle>();
//设置速度
vehicleComponent.SetPath(Speed,length);
}
/// <summary>
/// 获取相应位置
/// </summary>
/// <returns></returns>
Vector3 GetPositionOffset(){
//方向和位置;
Vector3 positionOffset = transform.position;
//车向上位置
positionOffset += heightOffset * Vector3.up*0.95f ;
//车左边位置
positionOffset += StartOffset * Vector3.right;
return positionOffset;
}
/// <summary>
/// 协程
/// </summary>
/// <returns></returns>
IEnumerator Spawn() {
while (true)
{
// int vehicleIndex = Random.Range(0,vehiclePrefabs.Length); ;
// InstantiateVehicle(vehicleIndex);
// yield return new WaitForSeconds(5.0f);
//随机时间
WaitForSeconds radomWait = new WaitForSeconds(Random.Range(0.5f,maxSpwanTime));
yield return radomWait;
int vehicleIndex = Random.Range(0,vehiclePrefabs.Length); ;
InstantiateVehicle(vehicleIndex);
}
}
void Update () {
}
}