Vuforia学习

Android TV Vuforia不支持

DefaultTrackableEventHandler脚本下

  • 动画跟随物体生成
public GameObject aiXiPrefab; 
//找到了需要识别的物体
    protected virtual void OnTrackingFound()
    {
        GameObject aiXi = GameObject.Instantiate(aiXiPrefab);
        aiXi.transform.position = this.transform.position;
        aiXi.transform.parent = this.transform;
    }
  • 物体销毁
//丢失了需要识别的物体
    protected virtual void OnTrackingLost()
    {
        Destroy(GameObject.Find("AiXi(Clone)"));  
    }
  • 特效生成以及销毁(10秒后销毁和辨识物消失销毁),e1e2分别为两个特效
     public GameObject bloodPrefab;
        public GameObject tonadoPrefab;
    //找到了需要识别的物体
        protected virtual void OnTrackingFound()
        {
            GameObject aiXi = GameObject.Instantiate(aiXiPrefab);
            aiXi.transform.position = this.transform.position;
            aiXi.transform.parent = this.transform;
    
            GameObject e1 = GameObject.Instantiate(bloodPrefab, transform.position, Quaternion.identity);
            e1.transform.parent = this.transform;
            Destroy(e1, 10.0f);     //10秒后销毁
    
            GameObject e2 = GameObject.Instantiate(tonadoPrefab, transform.position, Quaternion.identity);
            e2.transform.parent = this.transform;
            Destroy(e2, 10.0f);
        }
    
    
    
    
    //丢失了需要识别的物体
        protected virtual void OnTrackingLost()
        {
            Destroy(GameObject.Find("aiXi(Clone)"));
            Destroy(GameObject.Find("RFX_Blood_Puddle(Clone)"));
            Destroy(GameObject.Find("RFX_Tonado_Flame(Clone)"));
        }
  • 物体上升

    public class Player : MonoBehaviour {
    
    	
    	void Update () {
            if (transform.localPosition.y>0)    //达到目标位置
            {
                return;
            }
            //物体上升
            transform.Translate(new Vector3(0, 1, 0) * Time.deltaTime);
    	}
    }
    
    
     protected virtual void OnTrackingFound()
        {
            GameObject aiXi = GameObject.Instantiate(aiXiPrefab,transform.position-new Vector3(0,1.6f,0),transform.rotation);//跟着这个脚本的物体旋转
            aiXi.transform.position = this.transform.position;
            aiXi.transform.parent = this.transform;
    
  • 阴影制作(透明材质)

创建一个Render Texture 指定给Camera的Rebdering Texture

把Render Texture制定给一个Plane

把Camera的Clear Flags设置为Solid Color

Plane的材质改为 Legacy shaders/Transparent/Diffuse

给要生成的物体设置层级Layer

camera只渲染要生成的物体层

调整plane的位置

Camera的Field of View调整影子的大小

  • 添加音效

在识别物是添加Audio Source组建添加音乐取消Play On Awake


public class MyDefaultTrackableEventHandler : MonoBehaviour, ITrackableEventHandler{


private AudioSource audio;  //声音组件

protected virtual void Start()
    {
       
        audio = this.GetComponent<AudioSource>();
       
    }


 protected virtual void OnTrackingFound()
    {
        if (!audio.isPlaying)
        {
            audio.Play();
        }
    }
}

public class Player : MonoBehaviour {

 private AudioClip welcomeClip;  //音乐片段

    private void Start()
    {
        Invoke("PlayWecomeClip", 6.0f);
    }

private void PlayWecomeClip()
    {
        AudioSource.PlayClipAtPoint(welcomeClip, transform.position);
    }
}

Clip赋值

  • 单击和双击(物体消失)

要点击的物体添加collider

public class Touch : MonoBehaviour 
{	
	void Update () 
   {
        if (Input.GetMouseButtonDown(0))
        {
            //发射射线
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            //接收信息
            RaycastHit hit;
            //如果射线碰撞到了东西
            if (Physics.Raycast(ray,out hit))
            {
                //单击
                if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began) ;    //几个手指碰到屏幕,phase刚点击,Began刚开始
                {
                    //双击
                    if (Input.GetTouch(0).tapCount==2)  //tapCount判断点击次数
                    Destroy(hit.collider.gameObject);
                }
            }
        }
	}
}
  • 长按
 private float touchTime;    //记录按下时间
 private bool newTouch = false;      //是否为新按下

//长按
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            //发射射线
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            //接收信息
            RaycastHit hit;
            //如果射线碰撞到了东西
            if (Physics.Raycast(ray, out hit))
            {
                //长按
                if (Input.touchCount==1)
                {
                    //获取点击屏幕的事件
                    Touch touch = Input.GetTouch(0);

                    //如果是刚开始按下
                    if (touch.phase==TouchPhase.Began)
                    {
                        newTouch = true;
                        touchTime = Time.time;
                    }
                    //手指按住的地方没有动
                    else if (touch.phase==TouchPhase.Stationary)
                    {
                        if (newTouch==true&&Time.time-touchTime>1f)
                        {
                            newTouch = false;
                            Destroy(hit.collider.gameObject);
                        }
                    }
                    else
                    {
                        newTouch = false;
                    }
                }
            }
        }
    }
  • 模型大小与生成的不一致

主要在于识别物体的Scale

  • 旋转

给物体添加脚本

public class Rotate : MonoBehaviour {

    float xSpeed = 150f;
	
	void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            if (Input.touchCount==1)
            {
                if (Input.GetTouch(0).phase==TouchPhase.Moved)  //一个手指触摸划动
                {
                    transform.Rotate(Vector3.up * Input.GetAxis("Mouse X") * -xSpeed * Time.deltaTime, Space.World);
                }
            }
        }
	}
}
  • 放大缩小
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnLarge : MonoBehaviour {

    Vector2 oldPos1;
    Vector2 oldPos2;
    	
	void Update () {
        if (Input.touchCount==2)
        {
            if (Input.GetTouch(0).phase==TouchPhase.Moved||Input.GetTouch(1).phase==TouchPhase.Moved)   //第一个或第二个手指移动
            {
                //当前手指位置
                Vector2 temPos1 = Input.GetTouch(0).position;
                Vector2 temPos2 = Input.GetTouch(1).position;

                if (isEnlarge(oldPos1,oldPos2,temPos1,temPos2))
                {
                    float oldScale = transform.localScale.x;
                    float newScale = oldScale * 1.025f;

                    transform.localScale = new Vector3(newScale, newScale, newScale);
                }
                else
                {
                    float oldScale = transform.localScale.x;
                    float newScale = oldScale / 1.025f;

                    transform.localScale = new Vector3(newScale, newScale, newScale);
                }
                oldPos1 = temPos1;
                oldPos2 = temPos2;

            }
        }
	}
    
    // 判断手势    
    bool isEnlarge(Vector2 oP1,Vector2 oP2,Vector2 nP1,Vector2 nP2)
    {
        float length1 = Mathf.Sqrt((oP1.x - oP2.x) * (oP1.x - oP2.x) + (oP1.y - oP2.y) * (oP1.y - oP2.y));//开始位置长度
        float length2 = Mathf.Sqrt((nP1.x - nP2.x) * (nP1.x - nP2.x) + (nP1.y - nP2.y) * (nP1.y - nP2.y));//结束位置长度

        if (length1<length2)
        {
            return true;
        }
        else
        {
           return false;
        }
    }
}
  • 截屏不显示截屏按钮

创建一个UI截屏Button和新的UIcamera只渲染UI层;(UIcamera使用O的Prejection,depth大于ARcamera,Clear Flags为depth onlt)canvas指定摄像机UIcamera

创建脚本指定事件;

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

public class ScreenShot : MonoBehaviour {
    private Camera arCamera;

    private void Start()
    {
        arCamera = GameObject.Find("ARCamera").GetComponent<Camera>();
    }
    //自定义命名规范

    //点击按钮触发此函数
    public void OnScreenShotClick()
    {
        //系统当前时间
        System.DateTime now = System.DateTime.Now;
        string times = now.ToString();  //转换为字符串
        times = times.Trim();   //去掉空格
        times = times.Replace("/", "-");    //把/替换成-

        //文件名
        string fileName = "ARScreenShot" + times + ".png";

        //是否是Android平台
        if (Application.platform==RuntimePlatform.Android)
        {


            //包含UI的方式
            ////截取屏幕到一张贴图上
            //Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);//1,2为屏幕的宽高,3图片纹理,4映射
            ////读取贴图
            //texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height),0, 0);
            ////应用一下
            //texture.Apply();

            ////存储图片信息
            //byte[] bytes = texture.EncodeToPNG();
            ////目录
            //string destination = "/sdcard/DCIM/ScreenShots";   //自己创建的文件夹不会在相册显示,ScreenShots为系统自带截屏文件夹
            ////判断目录是否存在
            //if (!Directory.Exists(destination))
            //{
            //    Directory.CreateDirectory(destination);
            //}
            ////保存的路径
            //string pathSave = destination + "/" + fileName;
            ////完成保存
            //File.WriteAllBytes(pathSave, bytes);


            //不包含UI的方式

            //创建RenderTexture

            RenderTexture rt = new RenderTexture(Screen.width, Screen.height, 1);
            arCamera.targetTexture = rt;    //指定
            arCamera.Render();
            RenderTexture.active = rt;
            

            //截取屏幕到一张贴图上
            Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);//1,2为屏幕的宽高,3图片纹理,4映射
            
            texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);//读取贴图

            texture.Apply();//应用一下

            //重置
            arCamera.targetTexture = null;
            RenderTexture.active = null;
            Destroy(rt);

            //存储图片信息
            byte[] bytes = texture.EncodeToPNG();
            //目录
            string destination = "/sdcard/DCIM/ScreenShots";   //自己创建的文件夹不会在相册显示,ScreenShots为系统自带截屏文件夹
            
            if (!Directory.Exists(destination))//判断目录是否存在
            {
                Directory.CreateDirectory(destination);
            }
            
            string pathSave = destination + "/" + fileName;//保存的路径
            
            File.WriteAllBytes(pathSave, bytes);//完成保存

        }
    }
}
  • 摄像机的一些设置
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Vuforia
{
    public class CameraSetting : MonoBehaviour
    {

        
        void Start()
        {
            var vuforia = VuforiaARController.Instance;//单例模式
            //回调函数
            vuforia.RegisterVuforiaStartedCallback(OnVuforiaStarted);//当程序启动完成我们做什么
            vuforia.RegisterOnPauseCallback(OnPaused);//当程序暂停我们做什么
        }

        

        private void OnVuforiaStarted()
        {
            //自动对焦
            CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO);
        }

        private void OnPaused(bool isPaused)
        {

        }

        public void OnFocusModeClick()
        {
            //点击按钮对焦一次
            CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_TRIGGERAUTO);
        }

        //切换摄像头 已经不支持
        public void SwitchCameraDirection(CameraDevice.CameraDirection direction)
        {
            CameraDevice.Instance.Stop();//停止
            CameraDevice.Instance.Deinit();//取消初始化

            // CameraDevice.Instance.Init(CameraDevice.CameraDirection.CAMERA_FRONT);//初始化前置摄像头
            CameraDevice.Instance.Init(direction);
            CameraDevice.Instance.Start();
        }

        //控制闪光灯
        public void FlashTouch(bool ON)
        {
            CameraDevice.Instance.SetFlashTorchMode(ON);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42459006/article/details/83315434