AR開發(fā)實戰(zhàn)Vuforia項目之PokemonGo(二、基于Lbs圖塊機制的實現(xiàn))

一、框架視圖

二、關(guān)鍵代碼

1、AR

AR_Au

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AR_Au : MonoBehaviour {

    public static AR_Au Instance; //單例模式

    private AudioSource AuS; //對聲音持有引用


     void Awake()
    {
        Instance = this;//單例模式 賦值    
    }

    void Start () {

        AuS = gameObject.transform.GetComponent<AudioSource>(); //聲音組件賦值
    }
    
    
    void Update () {
        
    }

    /// <summary>
    /// 播放聲音的事件函數(shù)
    /// </summary>
    public void BtnAuPlay() {

        AuS.Play();
    }
}

AR_UIMgr

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class AR_UIMgr : MonoBehaviour {

    public static AR_UIMgr Instance; //單例模式

    public Text Tx_BallNum; //儲存顯示精靈球數(shù)量的Text組件

    public Text Tx_FoodNum; //儲存顯示食物數(shù)量的Text組件

    public GameObject PnCatch; //小精靈捕捉成功的面板

    public Text InputPetName;//輸入精靈名字的組件

    private void Awake()
    {
        Instance = this; //單例模式
    }

    void Start () {
        
    }
    
    
    void Update () {
        
    }

    /// <summary>
    /// 返回地圖按鈕事件
    /// </summary>
    public void Btn_GoMapScn() {

        AR_Au.Instance.BtnAuPlay();//聲音播放事件
        SceneManager.LoadScene("PKGOMain");
    }

    /// <summary>
    /// 刷新精靈球的數(shù)量事件
    /// </summary>
    public void UpdateUIBallNum() {

        Tx_BallNum.text = StaticData.BallNum.ToString();    //把精靈球數(shù)量的全集數(shù)據(jù)顯示在UI中
    }


    /// <summary>
    /// 刷新食物的數(shù)量事件
    /// </summary>
    public void UpdateUIFoodNum() {

        Tx_FoodNum.text = StaticData.FoodNum.ToString(); //把食物數(shù)量的全局數(shù)據(jù)顯示在UI中 
    }



    /// <summary>
    /// 顯示小精靈的捕捉成功的面板
    /// </summary>
    public void Show_PnCatch() {

        PnCatch.SetActive(true);
    }


    /// <summary>
    /// 捕捉小精靈的確認按鈕
    /// </summary>
    public void Btn_Yes() {

        AR_Au.Instance.BtnAuPlay();//點擊按鈕的特效事件

        //Debug.Log("輸入的名字:"+InputPetName.text);
        string _name = InputPetName.text; //從輸入框獲取小精靈的名字

        int _index = StaticData.CatchingPetIndex; //從全局腳本中獲取正在捕捉小精靈在預(yù)制體集合中的序號

        StaticData.AddPet(new PetSave(_name,_index));//從全局數(shù)據(jù)的小精靈列表中添加一條小精靈屬性類數(shù)據(jù)

        SceneManager.LoadScene("Store_Scn"); //跳轉(zhuǎn)到倉庫場景
    }


    /// <summary>
    /// 放生按鈕的函數(shù)
    /// </summary>
    public void Btn_GiveUp() {

        AR_Au.Instance.BtnAuPlay();//播放放生按鈕的聲效
        SceneManager.LoadScene("PKGOMain"); //跳回地圖場景
    }


    /// <summary>
    /// 進入倉庫的按鈕
    /// </summary>
    public void Btn_ToStore() {

        AR_Au.Instance.BtnAuPlay(); //播放進去倉庫的聲效
        SceneManager.LoadScene("Store_Scn"); //進入倉庫場景
    }




}

ARBallCtrl

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ARBallCtrl : MonoBehaviour {


    public static ARBallCtrl Instance; //單例模式

    public Transform PosInsBall;    //儲存生成精靈球的位置

    private GameObject[] balls; //儲存精靈球的預(yù)制體


    private void Awake()
    {
        Instance = this; //單例模式
    }

    void Start () {

        balls = Resources.LoadAll<GameObject>("Balls");

        AR_UIMgr.Instance.UpdateUIBallNum(); //刷新精靈球的數(shù)量

        InsNewBall(); //執(zhí)行測試下

        //PosInsBall.transform.parent.transform.localRotation = Quaternion.identity; //默認相機不能旋轉(zhuǎn)

    }
    
    
    void Update () {
        
    }

    /// <summary>
    /// 生成精靈球
    /// </summary>
    public void InsNewBall() {

        if (StaticData.BallNum>0) //只有大于0 的情況下 才執(zhí)行實例化精靈球
        {
            GameObject _ball = Instantiate(balls[0], PosInsBall.position, PosInsBall.rotation); //實例化精靈球
            _ball.transform.SetParent(PosInsBall); //設(shè)置精靈球的父級物體 為了保證發(fā)射前在屏幕的固定位置
            _ball.gameObject.AddComponent<SphereCollider>();    //給球體增加球型碰撞器
            _ball.gameObject.GetComponent<SphereCollider>().radius = 0.01f; //設(shè)置碰撞觸發(fā)器半徑的大小
           // _ball.gameObject.AddComponent<ARShootBall>(); //添加發(fā)射球的控制腳本

            _ball.gameObject.transform.localScale = new Vector3(25f, 25f, 25f); //原預(yù)制體不變 動態(tài)改變尺寸的大小 縮放比例

        }
       
    }



}

ARFoodCtrl

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ARFoodCtrl : MonoBehaviour {

    public static ARFoodCtrl Instance;      //單例模式

    public Transform PosInsFood; //儲存生成食物的位置

    private GameObject[] foods; //儲存食物的預(yù)制體


    void Awake()
    {
        Instance = this;
    }


    void Start () {

        foods = Resources.LoadAll<GameObject>("Foods"); //加載所有的食物

        AR_UIMgr.Instance.UpdateUIFoodNum(); //刷新食物的數(shù)量

    }
    

    void Update () {
        
    }

    /// <summary>
    /// 生成新的食物
    /// </summary>
    public void InsNewFood() {


        if (StaticData.FoodNum>0) //如果食物大于0 的話才生成
        {

        }
    }
}

ARInsPets

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ARInsPets : MonoBehaviour {

    public Transform[] traPos; //儲存預(yù)制體的位置

    private GameObject[] pets;//儲存所有的精靈預(yù)制體

    public Transform CameraTra;//AR攝像機的位置

    void Start () {

        pets = Resources.LoadAll<GameObject>("Pets"); //加載所有的精靈預(yù)制體

        InsPet();//生成捕捉小精靈

        checkDis(); //檢查距離
    }
    



    
    void Update () {
        
    }

    /// <summary>
    /// 生成精靈
    /// </summary>
    public void InsPet() {

        int _index = Random.Range(0,traPos.Length); //隨機位置

        Transform _tra = traPos[_index]; //得到隨機位置

        GameObject _pet=Instantiate(pets[StaticData.CatchingPetIndex],_tra.position,_tra.rotation);   //實例化隨機生成的位置上的小精靈 注意預(yù)制體數(shù)組的位置

        _pet.transform.localScale = new Vector3(0.5f,0.5f,0.5f); //生成的預(yù)制體可以縮小到0.5倍

        Debug.Log("生成小精靈的名字:::;" +_pet.name);

        _pet.transform.LookAt(new Vector3(CameraTra.position.x,_pet.transform.position.y,CameraTra.position.z)); //讓生成的小精靈面朝玩家

       
    }

    /// <summary>
    /// 檢查每個生成小精靈的預(yù)支點到攝像機的距離
    /// </summary>
    private void checkDis() {

        foreach (Transform pos in traPos)
        {
            float _dis = Vector3.Distance(pos.position,CameraTra.position);
            Debug.Log("檢查預(yù)支點和攝像機的距離:"+_dis);
        }
    }
}

ARShootBall

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ARShootBall : MonoBehaviour {

    public float FwdForce = 200f; //設(shè)置給小球向前的力的大小

    public Vector3 StanTra = new Vector3(0,1f,0);   //設(shè)置夾角的參照數(shù)值

    private bool blTouched = false;//判斷手指是否觸碰了精靈球的位置

    private bool blShooted = false;//判斷精靈球是否可以發(fā)射

    private Vector3 startPosition; //手指滑動的起始點

    private Vector3 endPosition;    //手指滑動的終點

    private float disFick; //記錄手指滑動的距離

    private Vector3 offset; //記錄手指的偏移量

    private int timeFick;   //用幀數(shù)來記錄手指滑動的時間

    private float speedFick;//記錄滑動的速度

    private Camera camera;//記錄主攝像機

    void Start () {

        camera = Camera.main; //給主攝像機賦值
    }
    

    void Update () {

        if (blTouched) //如果按在小球上 允許計算手指滑動
        {
            slip();
        }
    }

    /// <summary>
    /// 重置參數(shù)
    /// </summary>
    private void resetVari() {

        startPosition = Input.mousePosition; // 起始位置設(shè)置為手指按下的位置

        endPosition = Input.mousePosition;  //終點位置設(shè)置為手指按下的位置


    }

    /// <summary>
    /// 鼠標(手指)按下 (是否觸碰到腳本掛載的物體)
    /// </summary>
    private void OnMouseDown()
    {
        if (blShooted==false) //精靈球尚未發(fā)射
        {
            blTouched = true;//允許檢測手指滑動
        }
    }


    /// <summary>
    /// 計算手指滑動的距離
    /// </summary>
    private void slip() {

        timeFick += 25; //時間每幀增加25  通過測試得出的數(shù)值

        if (Input.GetMouseButtonDown(0)) //當手指按下的時候
        {
            resetVari();    //重置參數(shù)
        }

        if (Input.GetMouseButton(0)) //當手指一直持續(xù)按在屏幕的時候
        {
            endPosition = Input.mousePosition;//把手指的終點位置變量 賦值刷新為當前手指所處的位置
            offset = camera.transform.rotation * (endPosition-startPosition);//獲取手指在世界坐標的偏移向量
            disFick = Vector3.Distance(startPosition,endPosition);//計算手指滑動的距離
        }

        if (Input.GetMouseButtonUp(0)) //當手指抬起的時候
        {
            speedFick = disFick / timeFick; //計算滑動的速度
            blTouched = false;//手指是否觸碰到精靈球 設(shè)置為否
            timeFick = 0;//時間記錄為零
            if (disFick>20&&endPosition.y-startPosition.y>0)  //r如果手指一動距離大于20 并且方向是向上滑動  防止誤碰精靈球而讓精靈球消失
            {
                shootBall(); //發(fā)射精靈球
            }


        }
    }


    /// <summary>
    /// 發(fā)射精靈球
    /// </summary>
    private void shootBall() {

        transform.gameObject.AddComponent<Rigidbody>(); //精靈球添加剛體
        Rigidbody _rigBall = transform.GetComponent<Rigidbody>(); //獲取剛體的組件
        //_rigBall.velocity = offset * 0.003f * speedFick; //給剛體添加一個速度
        _rigBall.velocity = offset.normalized * speedFick; //normalized只獲取向量的方向 沒有值
        _rigBall.AddForce(camera.transform.forward*FwdForce); //給攝像機位置一個向前的力
        _rigBall.AddTorque(transform.right); //添加轉(zhuǎn)矩  就是讓精靈球旋轉(zhuǎn)起來 有動態(tài)的感覺
        _rigBall.drag = 0.5f;//設(shè)置角阻力
        blShooted = true;//已經(jīng)發(fā)射 表示在拖動精靈球 不可能有發(fā)射的效果了
        transform.parent = null; //脫離父級物體 設(shè)置父類為空 可以自由活動 免得不在偏移

        StaticData.BallNum--; //發(fā)射之后數(shù)量減一
        AR_UIMgr.Instance.UpdateUIBallNum(); //更新精靈球的數(shù)量在UI中的顯示


        //ARBallCtrl.Instance.InsNewBall(); //單例 生成新的精靈球
        StartCoroutine(LateInsBall()); //開啟延遲生成精靈球的函數(shù)

        Destroy(_rigBall.transform.gameObject,5f); //5秒之后銷毀發(fā)射的精靈球 
        //Debug.Log("是否銷毀精靈球?");

    }


    /// <summary>
    /// 延遲重新生成精靈球 
    /// </summary>
    /// <returns></returns>
    IEnumerator LateInsBall() {

        yield return new WaitForSeconds(0.2f);  //延遲0.2秒
        ARBallCtrl.Instance.InsNewBall(); //單例模式  生成心的精靈球

    }




  

}

2、Login

Login_Au

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Login_Au : MonoBehaviour {

    public static Login_Au Instance; //單例模式

    private AudioSource AuS; //控制登錄的聲音

    void Awake()
    {
        Instance = this;//單例模式賦值
    }


    void Start () {

        AuS = gameObject.transform.GetComponent<AudioSource>();
    }
    
    
    void Update () {
        
    }

    /// <summary>
    /// 播放登錄聲音的事件
    /// </summary>
    public void BtnAuPlay() {

        AuS.Play();
    }

}

Login_UI

  using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Login_UI : MonoBehaviour {


    void Start () {
        
    }
    

    void Update () {
        
    }

    /// <summary>
    /// 登錄地圖場景
    /// </summary>
    public void Btn_ToMap() {

        Login_Au.Instance.BtnAuPlay();  //播放登錄的聲效
        SaveAndLoad.Load(); //靜態(tài)讀取全局數(shù)據(jù)的方法 在聲音后面執(zhí)行
        SceneManager.LoadScene("PKGOMain"); //跳轉(zhuǎn)到地圖場景
    }


}
3、Map
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ball_Find : MonoBehaviour {


    void Start () {
        
    }
    
    
    void Update () {
        
    }

    /// <summary>
    /// 觸發(fā)器檢測
    /// </summary>
    /// <param name="coll"></param>
    private void OnTriggerEnter(Collider coll)
    {
        if (coll.tag=="Avatar")  //觸發(fā)器 檢測到標簽是“Avatar” 則
        {
            UI_Mgr_02.Instance.AddBallNum(); //調(diào)用單例模式增加精靈球的數(shù)量
            Destroy(gameObject); //精靈球消失
        }
    }

}

BoyCtrl

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


/// <summary>
/// 腳本掛在主角上
/// </summary>
public class BoyCtrl : MonoBehaviour {

    private Animator mAnimator;
    //定義動畫控制器


    private MoveAvatar mMoveAvatar;
    //儲存角色的移動類 為了獲取角色移動的狀態(tài)


    void Start () {


        mAnimator = gameObject.transform.GetComponent<Animator>();
        //給動畫狀態(tài)機賦值 獲取角色控制器的組件

        mMoveAvatar = gameObject.transform.parent.GetComponent<MoveAvatar>();
        //給移動類賦值 父類上的組件 獲取移動的狀態(tài)類 獲取父父物體上的角色控制器的角色移動類

        
    }
    
    
    void Update () {

        if (mMoveAvatar.animationState==MoveAvatar.AvatarAnimationState.Idle) // 枚舉  如果是動畫狀態(tài)機中角色動畫狀態(tài)是定義中的待機狀態(tài) 則
        {

            if (!mAnimator.GetCurrentAnimatorStateInfo(0).IsName("Idle")) //如果當前播放動畫不是 待機狀態(tài)  則設(shè)置 觸發(fā)當前的待機動畫 注意前面是 非 感嘆號
            {
                mAnimator.SetTrigger("Idle"); //觸發(fā)動畫狀態(tài)機中的待機動畫
            }

        }
        else if (mMoveAvatar.animationState==MoveAvatar.AvatarAnimationState.Walk) //如果是動畫狀態(tài)機中角色的狀態(tài)是定義中的走路狀態(tài) 則
        {

            if (!mAnimator.GetCurrentAnimatorStateInfo(0).IsName("Walk")) //如果當前播放的動畫不是行走 則設(shè)置 觸發(fā)當前行走的動畫 注意加感到好 非 布爾值
            {
                mAnimator.SetTrigger("Walk"); //觸發(fā)動畫狀態(tài)機中的走路動畫
            }
           
        }
        else if (mMoveAvatar.animationState==MoveAvatar.AvatarAnimationState.Run) //如果是動畫狀態(tài)機中角色的狀態(tài)是定義中的跑步狀態(tài) 則
        {
            if (!mAnimator.GetCurrentAnimatorStateInfo(0).IsName("Run")) //如果當前播放的動畫不是跑步 則設(shè)置 觸發(fā)當前跑步的動畫  注意非  布爾值
            {
                mAnimator.SetTrigger("Run"); //觸發(fā)動畫狀態(tài)機中的跑步動畫
            }
         
        }


    }
}

DynamicLoadEvent

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GoShared;

public class DynamicLoadEvent : MonoBehaviour {


    public GameObject InsCube; //動態(tài)加載放置進地圖的3D盒子

    void Start () {
        
    }
    
    
    void Update () {
        
    }


    /// <summary>
    /// 把u3d的位置轉(zhuǎn)化為經(jīng)緯度坐標
    /// </summary>
    public void CheckPosition()
    {
        GameObject _avatar = GameObject.FindGameObjectWithTag("Avatar"); //查到角色游戲?qū)ο?
        Vector3 _avatarV3 = _avatar.transform.position; //獲取游戲?qū)ο蟮漠斍拔恢?
        Coordinates _coordinates = Coordinates.convertVectorToCoordinates(_avatarV3); //通過Vector3類型的坐標 轉(zhuǎn)化成經(jīng)緯度坐標

        Debug.Log("緯度 Avatar Latitude:" + _coordinates.latitude + "經(jīng)度:Avatar Longitude:" + _coordinates.longitude);
        //把轉(zhuǎn)化好的經(jīng)緯度顯示在控制臺上

    }

    /// <summary>
    /// 動態(tài)加載 盒子
    /// </summary>
    public void SetCube()
    {

        Coordinates _coordinates = new Coordinates(22.5780563, 113.8649978, 0); //設(shè)置好經(jīng)緯度  參數(shù)1:緯度 參數(shù)2:經(jīng)度 參數(shù)3:默認為 0
        
        Vector3 _v3 = _coordinates.convertCoordinateToVector(0); //把經(jīng)緯度轉(zhuǎn)化成游戲中的坐標

        GameObject _cube = Instantiate(InsCube); //生成預(yù)制體盒子

        _cube.transform.position = _v3; //設(shè)置盒子的位置



    }



}

Food_Find

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Food_Find : MonoBehaviour {


    void Start () {
        
    }
    
    
    void Update () {
        
    }

    /// <summary>
    /// 食物觸發(fā)事件
    /// </summary>
    /// <param name="coll"></param>
    private void OnTriggerEnter(Collider coll)
    {
        if (coll.tag=="Avatar") //如果檢測到人的出觸發(fā)器 
        {
            UI_Mgr_02.Instance.AddFoodNum();    //則調(diào)用單例模式中食物增加的方法
            Destroy(gameObject); //食物消失
        }
    }
}

InsPets

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InsPets : MonoBehaviour {

    public  GameObject[] Pets;

    //游戲啟動時候加載所有的精靈資源
    void Awake()
    {
        Pets = Resources.LoadAll<GameObject>("Pets"); //參數(shù)1:加載資源的類型 參數(shù)2:文件下的路徑
    }

    void Start () {

        InsPet();//生成小精靈

    }
    

    void Update () {
        
    }


    /// <summary>
    /// 生成隨機精靈的函數(shù)
    /// </summary>
    private void InsPet() {

        int _petIndex = Random.Range(0,Pets.Length); //隨機生成一個精靈的下標序列號  序列號從0到所有小精靈的預(yù)制體數(shù)量中  隨機選擇

        Instantiate(Pets[_petIndex],transform.position,transform.rotation);  //實例化 生成小精靈

    }
}


InsPoint

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InsPoint : MonoBehaviour {

    //公有變量首字母大寫
    public GameObject Ava; //儲存地圖的角色

    public GameObject PrePoint; //儲存事件點的預(yù)制體

    public float MinDis = 10f; //儲存最小距離范圍值 3米

    public float MaxDis = 50f;//儲存最大距離范圍 50米

    //私有變量首字母小寫
    private Vector3 v3Ava; //儲存當前的角色的坐標位置


    
    void Start () {
        
    }
    
    
    void Update () {
        
    }


    /// <summary>
    /// 隨機生成預(yù)制體的方法 生成精靈的方法 隨機一段距離然后獲取距離的坐標位置信息
    /// </summary>
    public void InsPointFun() {

        Map_Au.Instance.BtnAuPlay();    //播放生成精靈的聲效

        v3Ava = Ava.transform.position;//獲取角色的當前位置的坐標信息

        float _dis = Random.Range(MinDis,MaxDis); //獲取隨機位置的信息 從最小距離到最大距離之間取一個隨機值  局部變量  首寫加下劃線“_”

        Vector2 _pOri = Random.insideUnitCircle; //從原點(0,0)的坐標上隨機獲取一個任意方向的向量

        Vector2 _pNor = _pOri.normalized; //獲取到向量單位的向量 只有方向,大小為1; 有方向 有值才能稱為向量

        Vector3 v3Point = new Vector3(v3Ava.x+_pNor.x*_dis,2.5f,v3Ava.z+_pNor.y*_dis); //算出隨機點的位置 因為值為1,所以要乘距離值 _pNor.x*_Dis隨即向量的X值  _pNor.y*Dis隨即向量的Y值; Y值取決要生成的游戲?qū)ο蟮拇笮?
        GameObject _pointMark = GameObject.Instantiate(PrePoint,v3Point,transform.rotation); //實例化游戲物體  參數(shù)1:預(yù)制體 參數(shù)2:位置坐標信息  參數(shù)3:旋轉(zhuǎn)方向為當前物體的旋轉(zhuǎn)方向
    }
}

Map_Au

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Map_Au : MonoBehaviour {

    public static Map_Au Instance;  //單例模式

    private AudioSource AuS; //定義聲音的組件

    void Awake()
    {
        Instance = this; //單例模式     
    }

    void Start () {

        AuS = gameObject.transform.GetComponent<AudioSource>(); //聲音組件的持有引用
    }
    

    void Update () {
        
    }

    /// <summary>
    /// 播放點擊按鈕的事件
    /// </summary>
    public void BtnAuPlay() {

        AuS.Play();

    }
}

MobileGyro

using UnityEngine;
using System.Collections;
//攝像機  陀螺儀轉(zhuǎn)動
public class MobileGyro : MonoBehaviour
{
    Gyroscope gyro;
    Quaternion quatMult;
    Quaternion quatMap;
    GameObject player;
    GameObject camParent;
    void Awake()
    {
        player = GameObject.Find("Player");
        // find the current parent of the camera's transform
        Transform currentParent = transform.parent;
        // instantiate a new transform
        camParent = new GameObject("camParent");
        // match the transform to the camera position
        camParent.transform.position = transform.position;
        // make the new transform the parent of the camera transform
        transform.parent = camParent.transform;
        // make the original parent the grandparent of the camera transform
        //camParent.transform.parent = currentParent;
        // instantiate a new transform
        GameObject camGrandparent = new GameObject("camGrandParent");
        // match the transform to the camera position
        camGrandparent.transform.position = transform.position;
        // make the new transform the parent of the camera transform
        camParent.transform.parent = camGrandparent.transform;
        // make the original parent the grandparent of the camera transform
        camGrandparent.transform.parent = currentParent;

        Input.gyro.enabled=true;
        gyro = Input.gyro;

        gyro.enabled = true;
        camParent.transform.eulerAngles = new Vector3(90,-135, 0);
       //camParent.transform.eulerAngles = new Vector3(90, 0, 180);
        //quatMult = new Quaternion(0, 0, 1, 0);
        quatMult = new Quaternion(0, 0, 1, 0);
    }

    void Update()
    {

        quatMap = new Quaternion(gyro.attitude.x, gyro.attitude.y, gyro.attitude.z, gyro.attitude.w);
        Quaternion qt=quatMap * quatMult;

        transform.localRotation =qt;

    }

}

MoveEffect

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


/// <summary>
/// 浮動旋轉(zhuǎn)的腳本
/// </summary>
public class MoveEffect : MonoBehaviour {

    private float radian = 0; //起始的弧度

    private float perRad = 0.03f;//弧度的變化值

    private float add = 0;  //儲存位置的偏移量

    private Vector3 posOri;//儲存物體生成時的真實坐標
    
    void Start () {

        posOri = transform.position;//把物體生成時的位置坐標信息記錄下來
    }
    
    
    void Update () {

        //radian += perRad;//弧度不斷增加

        //add = Mathf.Sin(radian); //得到弧度的偏移值

        //transform.position = posOri + new Vector3(0,add,0);//讓物體不斷浮動起來


        //transform.Rotate(0, Time.deltaTime * 25f,0,Space.World); //以世界坐標為旋轉(zhuǎn)依據(jù)  在Y軸上進行旋轉(zhuǎn)

        MoveEffeftFunc();
    }

    /// <summary>
    /// 讓物體旋轉(zhuǎn)上下浮動的效果
    /// </summary>
    private void MoveEffeftFunc() {

        radian += perRad;//弧度不斷增加

        add = Mathf.Sin(radian); //得到弧度的偏移值

        transform.position = posOri + new Vector3(0, add, 0);//讓物體不斷浮動起來


        transform.Rotate(0, Time.deltaTime * 25f, 0, Space.World); //以世界坐標為旋轉(zhuǎn)依據(jù)  在Y軸上進行旋轉(zhuǎn)
    }
}

Pet_Find

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Pet_Find : MonoBehaviour {

    public int Pet_Index;   //儲存小精靈的序列號
    
    void Start () {

        if (GameObject.FindGameObjectWithTag("Avatar"))
        {
            gameObject.transform.LookAt(GameObject.FindGameObjectWithTag("Avatar").transform); //讓精靈一開始朝向主角
        }
            
        
                  
    }
    

    void Update () {
        
    }


    /// <summary>
    /// 發(fā)現(xiàn)寵物的觸發(fā)器檢測
    /// </summary>
    /// <param name="coll">觸發(fā)物體</param>
    private void OnTriggerEnter(Collider coll)
    {
        if (coll.tag=="Avatar") //如果檢測到的物體是 主角則 設(shè)置捕捉面板的狀態(tài)
        {
            UI_Mgr_02.Instance.SetIm_Catch(true); //顯示捕捉面板
            UI_Mgr_02.Instance.Tx_PetName.text = StaticData.GetType(Pet_Index); //通過輸入序號賦值字符串給精靈的名稱
            StaticData.CatchingPetIndex = Pet_Index;//當碰到角色時 把小精靈的序列號賦值給靜態(tài)數(shù)據(jù)中正要捕捉的小精靈序號
            Destroy(gameObject); //銷毀精靈

        }

        if (coll.tag=="Ball")
        {
          //  Debug.Log("擊中小精靈了····");
            playCatched(); //播放動畫
            StartCoroutine(ShowCatchPn()); //開啟延遲顯示成功捕捉的畫面
        }
    }

    /// <summary>
    /// 延遲顯示成功捕捉面板并銷毀小精靈
    /// </summary>
    /// <returns></returns>
    IEnumerator ShowCatchPn() {

        yield return new WaitForSeconds(2f);
         AR_UIMgr.Instance.Show_PnCatch();   //顯示捕捉成功面板
        Destroy(transform.gameObject);//銷毀小精靈本身
    }

    /// <summary>
    /// 播放被捉到的畫面  私有函數(shù)首字母小寫
    /// </summary>
    private void playCatched() {
        transform.GetComponent<Animator>().SetTrigger("Catched");
    }

}



PointEvent

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 隨機生成點事件
/// </summary>
public class PointEvent : MonoBehaviour {

    // public GameObject Pet; //儲存小精靈的預(yù)制體
    public GameObject[] Pets; 

    //public GameObject Ball; //儲存精靈球的預(yù)制體
    public GameObject[] Balls;


    //public GameObject Food; //儲存食物的預(yù)制體
    public GameObject[] Foods;


    /// <summary>
    /// 動態(tài)加載食物 和精靈球  可以考慮用asssetbundle
    /// </summary>
     void Awake()
    {
        Pets = Resources.LoadAll<GameObject>("Pets"); //參數(shù)1:加載資源的類型 參數(shù)2:文件下的路徑
        Balls = Resources.LoadAll<GameObject>("Balls"); //加載所有的精靈球
        Foods = Resources.LoadAll<GameObject>("Foods"); // 加載所有的食物

    }




    void Start () {
        //申請局部變量 隨機生成事件
        int _randomEvent = Random.Range(0,3);
        if (_randomEvent==0)
        {
            InsPet();
        }
        else if (_randomEvent==1)
        {
            InsBall();
        }
        else if (_randomEvent==2)
        {
            InsFood();
        }


    }
    
    
    void Update () {
        
    }

    /// <summary>
    /// 生成小精靈
    /// </summary>
    private void InsPet() {

        int _petIndex = Random.Range(0, Pets.Length); //隨機生成一個精靈的下標序列號  序列號從0到所有小精靈的預(yù)制體數(shù)量中  隨機選擇
   
       GameObject _pet= Instantiate(Pets[_petIndex], transform.position, transform.rotation);  //實例化 生成小精靈
                                                                                               // Instantiate(Pet,transform.position,transform.rotation);

        _pet.transform.GetComponent<Pet_Find>().Pet_Index = _petIndex; //把生成的小精靈的序號傳遞給小精靈身上掛在的腳本
    }

    /// <summary>
    /// 生成精靈球
    /// </summary>
    private void InsBall() {

        int _ballIndex = Random.Range(0,Balls.Length);
       // Debug.Log("精靈球的下標:::::::::" + _ballIndex);
        GameObject _ball= Instantiate(Balls[_ballIndex], transform.position + new Vector3(0,5f,0),transform.rotation); //Y軸上面偏移5f距離

        //Debug.Log("精靈球的名稱:::::::::" + _ball.name); //精靈球碰撞器太大·導(dǎo)致數(shù)量直接增加
        _ball.transform.localEulerAngles = new Vector3(-30,0,0); //圍繞X軸旋轉(zhuǎn)了-30度

        _ball.AddComponent<SphereCollider>(); //增加碰撞器組件
        _ball.GetComponent<SphereCollider>().isTrigger = true; //設(shè)置為觸發(fā)器
        _ball.GetComponent<SphereCollider>().radius = 0.01f; //設(shè)置碰撞器的半徑  注意半徑的大小
        _ball.AddComponent<Rigidbody>();//添加剛體
        _ball.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeAll;//凍結(jié)剛體上所有物理的轉(zhuǎn)換效果
        _ball.AddComponent<MoveEffect>(); //添加運動特效的腳本
        _ball.AddComponent<Ball_Find>();    //添加發(fā)現(xiàn)精靈球的腳本

    }

    /// <summary>
    /// 生成食物
    /// </summary>
    private void InsFood() {
        int _foodIndex = Random.Range(0,Foods.Length);
       GameObject _food=Instantiate(Foods[_foodIndex],transform.position+new Vector3(0,5f,0),transform.rotation);//Y軸上偏移5f的距離

        _food.AddComponent<BoxCollider>();  //增加碰撞器組件
        _food.GetComponent<BoxCollider>().isTrigger = true; //設(shè)置為觸發(fā)器
        _food.GetComponent<BoxCollider>().center = new Vector3(0,0f,0);     //設(shè)置中心點的位置
        _food.GetComponent<BoxCollider>().size = new Vector3(0.33f,0.3f,0.33f); //設(shè)置碰撞器的大小尺寸
        _food.AddComponent<Rigidbody>();//添加剛體
        _food.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeAll; //凍結(jié)剛體所有物體的轉(zhuǎn)換
        _food.AddComponent<MoveEffect>();   //添加運動特效的腳本
        _food.AddComponent<Food_Find>();    //添加找到食物的腳本


    }





}

UI_Mgr_02

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class UI_Mgr_02 : MonoBehaviour {

    //單例模式
    public static UI_Mgr_02 Instance;


    public Text Tx_BallNum; //儲存精靈球的數(shù)量

    public Text Tx_FoodNum; //儲存食物的數(shù)量

    public GameObject Im_Catch; //儲存捕捉面版


    public Text Tx_PetName; //儲存精靈的名稱 

     void Awake()
    {
        Instance = this;   
    }

     void Start()
    {
        Tx_BallNum.text = StaticData.BallNum.ToString();// 一開始調(diào)用全局變量中的精靈球數(shù)量在UI中的顯示

        Tx_FoodNum.text = StaticData.FoodNum.ToString();    // 一開始調(diào)用全局變量中的 食物數(shù)量在UI中的顯示
    }


    /// <summary>
    /// 增加精靈球的數(shù)量
    /// </summary>
    public void AddBallNum() {

        //int _num = int.Parse(Tx_BallNum.text); //將字符串轉(zhuǎn)變成整型

        //_num++; //數(shù)量加加

        //Tx_BallNum.text = _num.ToString(); //文本賦值

        StaticData.BallNum++; //精靈球+1

        Tx_BallNum.text = StaticData.BallNum.ToString(); //顯示精靈球數(shù)量


    }

    /// <summary>
    /// 增加食物的數(shù)量
    /// </summary>
    public void AddFoodNum() {

        //int _num = int.Parse(Tx_FoodNum.text);  //將字符串轉(zhuǎn)換成整型

        //_num++; //數(shù)量加加

        //Tx_FoodNum.text = _num.ToString(); //數(shù)字轉(zhuǎn)換成字符串 賦值

        StaticData.FoodNum++; //食物+1;

        Tx_FoodNum.text = StaticData.FoodNum.ToString(); //顯示食物的數(shù)量


    }

    /// <summary>
    /// 設(shè)置捕捉面板的激活狀態(tài)
    /// </summary>
    /// <param name="bl"></param>
    public void SetIm_Catch(bool bl) {
        Map_Au.Instance.BtnAuPlay(); //跳轉(zhuǎn)的聲效
        Im_Catch.SetActive(bl); //通過參數(shù)來控制面板是隱藏還是顯示  參數(shù)是布爾類型
    }


    /// <summary>
    /// 跳轉(zhuǎn)到Ar場景
    /// </summary>
    public void Btn_GoARScn() {
        Map_Au.Instance.BtnAuPlay(); //跳轉(zhuǎn)的聲效
        SceneManager.LoadScene("Ar_Scn");
    }

    /// <summary>
    /// 跳轉(zhuǎn)到倉庫場景
    /// </summary>
    public void Btn_ToStore() {

        Map_Au.Instance.BtnAuPlay();//跳轉(zhuǎn)到倉庫的聲效
        SceneManager.LoadScene("Store_Scn");
    }


}

4、Pet

PetSave

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PetSave  {

    private string petName = "未命名寵物";  //記錄小精靈的名字

    private int petIndex = 0;//記錄小精靈在對應(yīng)的模型在集合中對應(yīng)的序列號


    /// <summary>
    /// 精靈名字的屬性
    /// </summary>
    public string PetName {
        get { return petName; }
        set { petName = value; }
    }


    /// <summary>
    /// 精靈序列號屬性
    /// </summary>
    public int PetIndex
    {
        get { return petIndex; }
        set { petIndex = value; }

    }



    /// <summary>
    /// 帶參數(shù)的構(gòu)造函數(shù)
    /// </summary>
    /// <param name="name">精靈名字的參數(shù)</param>
    /// <param name="index">精靈序列號</param>
    public PetSave(string  name,int index) {

        PetName = name;  //名字屬性賦值

        PetIndex = index;   //序列號屬性賦值
    }




}

5、Static

SaveAndLoad

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 靜態(tài)調(diào)用數(shù)據(jù)類
/// </summary>
public static class SaveAndLoad {


    /// <summary>
    /// 保存數(shù)據(jù)
    /// </summary>
    public static void Save() {

        ES3.Save<int>("BallNum", StaticData.BallNum); //保存精靈球的數(shù)量

        ES3.Save<int>("PetNum",StaticData.PetList.Count); //保存已經(jīng)捕捉小精靈的數(shù)量

        //保存每個已被捕捉精靈的相關(guān)信息
        for (int i = 0; i < StaticData.PetList.Count; i++)
        {

            ES3.Save<string>("PetNm" + i.ToString(), StaticData.PetList[i].PetName);
            ES3.Save<int>("PetIndex" + i.ToString(), StaticData.PetList[i].PetIndex);
        }
    }



    /// <summary>
    /// 讀取數(shù)據(jù)
    /// </summary>
    public static void Load() {
        
        if (ES3.KeyExists("BallNum")&&ES3.KeyExists("PetNum")) //先判斷它是否存在
        {
            StaticData.BallNum = ES3.Load<int>("BallNum");  //讀取精靈球的數(shù)量賦值給全局變量中

            int _petNum = ES3.Load<int>("PetNum"); //讀取到已經(jīng)捕捉到的精靈球數(shù)量

            //把存在的小精靈都賦值
            for (int i = 0; i <_petNum; i++)
            {
                string _petName = ES3.Load<string>("PetNm" + i.ToString()); //讀取精靈的名稱

                int _petIndex = ES3.Load<int>("PetIndex" + i.ToString()); //讀取精靈的下標

                StaticData.AddPet(new PetSave(_petName,_petIndex));  //把讀取到的精靈信息寫入保存的類中

            }


        }

    }


}

StaticData

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 靜態(tài)類
/// </summary>
public static class StaticData {

    public static int BallNum = 50; //精靈球數(shù)量的全局變量 初始化為5;

    public static int FoodNum = 20; //食物數(shù)量的全局變量 初始化為10;

    public static int CatchingPetIndex; //當前主要捕捉的小精靈在預(yù)制體集合中的序列號
    
    public static List<PetSave> PetList=new List<PetSave>(); //申請列表儲存的捕捉小精靈類

    /// <summary>
    /// 捕捉小精靈的添加到集中去  向全局數(shù)據(jù)中小精靈列表添加小精靈
    /// </summary>
    /// <param name="petsave">儲存小精靈的屬性類</param>
    public static void AddPet(PetSave petSave) {

        PetList.Add(petSave);
    }

    /// <summary>
    /// 通過小精靈在預(yù)制體集合中的序號來獲取它的精靈類型
    /// </summary>
    /// <param name="index">小精靈在集合中的序號</param>
    /// <returns>返回的類型</returns>
    public static string GetType(int index) {

        if (index == 0)
        {
            return "小熊";
        }
        else if (index == 1)
        {
            return "小牛";
        }
        else if (index == 2)
        {
            return "兔子";
        }
        else if (index == 3)
        {
            return "小雞";
        }
        else if (index == 4)
        {
            return "老虎";
        }
        else if (index == 5)
        {
            return "猴子";
        }
        else if (index == 6)
        {
            return "白貓";
        }
        else if (index == 7)
        {
            return "獅子";
        }
        else if (index == 8)
        {
            return "企鵝";
        }
        else if (index == 9)
        {
            return "犀牛";
        }
        else
        {
            return "小黃狗";
        }


        //switch (index)
        //{
        //    case 0:
        //        return "小熊";

        //    case 1:
        //        return "小牛";

        //    case 2:
        //        return "兔子";
        //    case 3:
        //        return "小雞";
        //    case 4:
        //        return "老虎";
        //    case 5:
        //        return "猴子";
        //    case 6:
        //        return "白貓";
        //    case 7:
        //        return "獅子";
        //    case 8:
        //        return "企鵝";
        //    case 9:
        //        return "犀牛";

        //    default:
        //        return "小黃狗";
        //}

    }

}

6、Store

Store_Au

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Store_Au : MonoBehaviour {

    public static Store_Au Instance;    //單例模式

    private AudioSource AuS;    //聲音組件持有的引用


     void Awake()
    {
        Instance = this; //單例模式    
    }

    void Start () {

        AuS = gameObject.transform.GetComponent<AudioSource>(); //聲音組件的賦值
    }
    

    void Update () {
        
    }

    /// <summary>
    /// 點擊按鈕的返回聲效事件
    /// </summary>
    public void BtnAuPlay() {

        AuS.Play(); //播放聲效的事件
    }


}


StoreInsPet

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class StoreInsPet : MonoBehaviour {

    public Transform[] Pos;//儲存寵物欄中小精靈的生成點

    private GameObject[] pets;//儲存所有精靈的預(yù)制體

    private GameObject[] petShow = new GameObject[3]; //在倉庫中顯示出來的小精靈

    void Awake()
    {
        pets = Resources.LoadAll<GameObject>("Pets"); //加載所有的小精靈
    }

    void Start () {

        InsPet(); //調(diào)用此方法在倉庫中的顯示 
    }
    

    void Update () {
        
    }

    /// <summary>
    /// 倉庫中生成小精靈的函數(shù)
    /// </summary>
    public void InsPet() {

        int _petNum = StaticData.PetList.Count;//通過全局變量儲存好的精靈數(shù)量來判斷 已經(jīng)捕捉好的精靈數(shù)量

        //只有數(shù)量大于0 的情況下才執(zhí)行如下方法
        if (_petNum>0)
        {
            for (int i = 0; i < petShow.Length; i++)
            {

                if (_petNum-1<i) //如果數(shù)量減1小于i  排列的順序不變  返回
                {
                    return;
                }


                PetSave _petInfo = StaticData.PetList[i]; //從全局類中 獲取對應(yīng)的序列號中的小精靈屬性   petsave類中儲存的是  名字和序列號

                Instantiate(pets[_petInfo.PetIndex],Pos[i].position,Pos[i].rotation); //實例化小精靈  游戲?qū)ο缶褪?全局變量中對應(yīng)的序列號的預(yù)制體   位置是生成的倉庫位置點

                string _petNm=_petInfo.PetName;   //獲取對應(yīng)中精靈的名字  以致調(diào)用刷新名字的方法

                StoreUIMgr.Instance.UpDatePetNm(i,_petNm);//刷新精靈的名字

                string _petType = StaticData.GetType(_petInfo.PetIndex); //獲取精靈的種類

                StoreUIMgr.Instance.UpDatePettype(i,_petType);  //刷新精靈的類型

            }

        }



    }
}

StoreUIMgr

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class StoreUIMgr : MonoBehaviour {


    public Text[] Tx_PetNm; //儲存精靈名字的數(shù)組

    public Text[] Tx_PetType; //儲存精靈類型的數(shù)組


    public static StoreUIMgr Instance; //單例模式

     void Awake()
    {
        Instance = this; //單例模式賦值  
    }

    void Start () {
        

    }
    
    
    void Update () {
        
    }

    /// <summary>
    /// 刷新小精靈的名字
    /// </summary>
    /// <param name="index">小精靈在數(shù)組中的序號</param>
    /// <param name="strNm">小精靈要顯示的名字</param>
    public void UpDatePetNm(int index,string strNm) {
        Tx_PetNm[index].text = strNm;
    }



  /// <summary>
  /// 刷新小精靈的類型
  /// </summary>
  /// <param name="index">在數(shù)組中小精靈的序號</param>
  /// <param name="strType">顯示小精靈的類型</param>
    public void UpDatePettype(int index,string strType) {

        Tx_PetType[index].text = strType;
    }



    /// <summary>
    /// 跳轉(zhuǎn)到場景中的按鈕
    /// </summary>
    public void Btn_ToMap() {

        Store_Au.Instance.BtnAuPlay(); //播放點擊按鈕的聲效
        SceneManager.LoadScene("PKGOMain"); //跳轉(zhuǎn)到主場景
    }

    /// <summary>
    /// 倉庫中保存按鈕
    /// </summary>
    public void Btn_Save() {

        SaveAndLoad.Save(); //保存數(shù)據(jù)的方法
    }

}

三、效果展示

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容