VR开发实战CardBoard项目之天天过马路

主要框架视图

关键代码

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 () {
        
    }
}

展示效果

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,236评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,867评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,715评论 0 340
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,899评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,895评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,733评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,085评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,722评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,025评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,696评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,816评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,447评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,057评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,009评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,254评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,204评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,561评论 2 343

推荐阅读更多精彩内容