VR開發(fā)實戰(zhàn)CardBoard項目之天天過馬路

主要框架視圖

關(guān)鍵代碼

FireWall

public class FireWall : MonoBehaviour {

    //火向前推進速度
    public float creepSpeed = 0.01f;

    //主角引用
    private Player player;

    //判斷游戲狀態(tài)
    private LevelState state;
    void Start () {
        player = GameObject.FindObjectOfType<Player>();
        state = GameObject.FindObjectOfType<LevelState>();
    }
    

    void Update () {
        //游戲沒結(jié)束

        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;

    //結(jié)束UI
    private Canvas canvas;

    //游戲狀態(tài)
    private LevelState state;
    

    void Start () {

        player = GameObject.FindObjectOfType<Player>();

        canvas = GetComponent<Canvas>();
        //畫面一開始不可用
        canvas.enabled = false;
        state = GameObject.FindObjectOfType<LevelState>();

    }
    
    void Update () {
        //判斷是否游戲結(jié)束
        if (state.isGameOver)
        {
            TrackPlayerHead();
            canvas.enabled = true;
        }
    

    }

    /// <summary>
    /// 追蹤主角頭部
    /// </summary>
    void TrackPlayerHead() {
        //結(jié)束UI畫面跟隨主角
        //旋轉(zhuǎn)
        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 {
    //分數(shù)引用
    public int hightScore;

    /// <summary>
    /// 加載時不要銷毀gamestate 三個場景共用
    /// </summary>
    private void Awake()
    {
        DontDestroyOnLoad(gameObject);
    }
    /// <summary>
    /// 更新分數(shù)的方法
    /// </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 () {
        //獲取分數(shù)
        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>
    /// 車碰到玩家及游戲結(jié)束
    /// </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 {
    //判斷游戲是否結(jié)束的字段
    public bool _isGameOver = false;

    //判斷游戲是否結(jié)束屬性
    public bool isGameOver{
        get { return _isGameOver; }
        set {
            if (value)
            {
                SetHightScore();
            }
            _isGameOver = true;
        }
    }
    /// <summary>
    /// 設(shè)置分數(shù)
    /// </summary>
    void SetHightScore() {

        GameState state = GameObject.FindObjectOfType<GameState>();
        Player player = GameObject.FindObjectOfType<Player>();
        //數(shù)學(xué)公式 將位置轉(zhuǎn)成數(shù)值
        int score = Mathf.FloorToInt(player.transform.position.z);
        state.UpdateHightScore(score);
    }

    //重新開始游戲
    public void ResetGame() {
        //SceneManager.LoadScene("Main");
        //重構(gòu)代碼
        ScenesLoder loader = GameObject.FindObjectOfType<ScenesLoder>();
        loader.LoadLevelByOffset(0);
    }

    //返回游戲
    public void BackGame(){
        //  SceneManager.LoadScene("SphashScreen");    
        //重構(gòu)代碼
        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;

    //獲取游戲狀態(tài)
    private LevelState state;
    void Start()
    {
        //觸發(fā)事件
        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>
    /// 觸發(fā)事件后的行為 盒子上的小彈片 點擊事件
    /// </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() {

        //判斷游戲不是結(jié)束狀態(tài)才可以眺陨倡,結(jié)束不能跳;
        if (!state.isGameOver)
        {
            //Jump
            //度轉(zhuǎn)弧度
            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);
    }

    //檢測是否碰撞到地面 避免在空中連續(xù)跳
    //private void OnCollisionEnter(Collision collision)
    //{
    //    onFloor = true;
    //}

    //private void OnCollisionExit(Collision collision)
    //{
    //    onFloor = false;
    //}

        /// <summary>
        /// 當(dāng)碰到物體時绎晃,判斷起跳時間
        /// </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 {

    //延遲調(diào)用時間 開始啟動
    public  float loadLevelAfterTime = 0;

    void Start () {
        //判斷時間大于零的話 調(diào)用場景
        if (loadLevelAfterTime>0)
        {
            Invoke("LoadNextLevel", loadLevelAfterTime);
        }
        
    }

    //調(diào)用場景的方法
    public void LoadNextLevel() {
        //調(diào)用指定場景
        //  SceneManager.LoadScene("Login");
        //當(dāng)前場景直接調(diào)轉(zhuǎn)下一場景
        //  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);
            //隨機的預(yù)制體
            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 () {
        //函數(shù)調(diào)用 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 {
    //此腳本掛在預(yù)制體道路上
    //定義公開的車輛
    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();
        //開啟協(xié)程
        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>();
        //設(shè)置速度
        vehicleComponent.SetPath(Speed,length);
    }
    /// <summary>
    /// 獲取相應(yīng)位置
    /// </summary>
    /// <returns></returns>
    Vector3 GetPositionOffset(){
        //方向和位置;
        Vector3 positionOffset = transform.position;
        //車向上位置
        positionOffset += heightOffset * Vector3.up*0.95f ;
        //車左邊位置
        positionOffset += StartOffset * Vector3.right;

        return positionOffset;
    }
    /// <summary>
    /// 協(xié)程
    /// </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 () {
        
    }
}

展示效果

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市硼砰,隨后出現(xiàn)的幾起案子欣硼,更是在濱河造成了極大的恐慌,老刑警劉巖诈胜,帶你破解...
    沈念sama閱讀 206,723評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件耘斩,死亡現(xiàn)場離奇詭異,居然都是意外死亡括授,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,485評論 2 382
  • 文/潘曉璐 我一進店門薛夜,熙熙樓的掌柜王于貴愁眉苦臉地迎上來版述,“玉大人,你說我怎么就攤上這事渴析。” “怎么了咆疗?”我有些...
    開封第一講書人閱讀 152,998評論 0 344
  • 文/不壞的土叔 我叫張陵母债,是天一觀的道長。 經(jīng)常有香客問我迅皇,道長衙熔,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,323評論 1 279
  • 正文 為了忘掉前任框咙,我火速辦了婚禮脖隶,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘产阱。我一直安慰自己,他們只是感情好构蹬,可當(dāng)我...
    茶點故事閱讀 64,355評論 5 374
  • 文/花漫 我一把揭開白布庄敛。 她就那樣靜靜地躺著,像睡著了一般藻烤。 火紅的嫁衣襯著肌膚如雪头滔。 梳的紋絲不亂的頭發(fā)上涎显,一...
    開封第一講書人閱讀 49,079評論 1 285
  • 那天期吓,我揣著相機與錄音,去河邊找鬼讨勤。 笑死,一個胖子當(dāng)著我的面吹牛潭千,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播逝段,決...
    沈念sama閱讀 38,389評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼割捅,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了嘹黔?” 一聲冷哼從身側(cè)響起莫瞬,我...
    開封第一講書人閱讀 37,019評論 0 259
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎疼邀,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體获询,經(jīng)...
    沈念sama閱讀 43,519評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡拐袜,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,971評論 2 325
  • 正文 我和宋清朗相戀三年蹬铺,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片甜攀。...
    茶點故事閱讀 38,100評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡琐馆,死狀恐怖印衔,靈堂內(nèi)的尸體忽然破棺而出姥敛,到底是詐尸還是另有隱情,我是刑警寧澤与帆,帶...
    沈念sama閱讀 33,738評論 4 324
  • 正文 年R本政府宣布墨榄,位于F島的核電站,受9級特大地震影響袄秩,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜郭卫,卻給世界環(huán)境...
    茶點故事閱讀 39,293評論 3 307
  • 文/蒙蒙 一背稼、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧蟹肘,春花似錦、人聲如沸贰盗。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,289評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽胸完。三九已至,卻和暖如春爆惧,著一層夾襖步出監(jiān)牢的瞬間锨能,已是汗流浹背爪模。 一陣腳步聲響...
    開封第一講書人閱讀 31,517評論 1 262
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留斋竞,地道東北人秃殉。 一個月前我還...
    沈念sama閱讀 45,547評論 2 354
  • 正文 我出身青樓钾军,卻偏偏與公主長得像鳄袍,于是被迫代替她去往敵國和親吏恭。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,834評論 2 345

推薦閱讀更多精彩內(nèi)容