1、生成下载资源包
开发2D跟踪和本地识图功能时,需要先生成跟踪模型。首先前往DuMix AR官网(http://dumix.baidu.com/console),上传图片,生成并下载资源包。过程如图所示:
下载的资源包和资源包包含的内容,如图所示:
注:下载的资源包的名字可以修改,但资源包内部的三个文件夹的名字不可以修改。
2、图片识别
a)、根据第一章创建一个场景,删掉场景的相机,把ARCamera prefab拖入场景中,填写APPID等参数(具体操作请看第一章)。
b)、在Hierarchy里创建一个空物体(我这把空物体改名了,改为ARImageRecognition),为该空物体添加BaiduARImageRecognition组件
组件讲解
OnErrorEvent事件:当识别出错会调用该事件
IntervalTime:摄像头调用的间隔
c)、在ARImageRecognition创建一个空物体,(我这把空物体改名了,改为Bear),添加一个BaiduARImageRecognitionResult组件,在FilePath上写上识别图的路径(识别图下载参考第一节,识别图只能导入在StreamingAssets文件夹里,路径填写StreamingAssets文件夹的相对路径)
如果想要从外部加载资源包,需要填写完整的路径,例如:“/Users/zhang/Desktop/picture/city/model/8e364efdba81cbec8ffed55b6f591d96_13042018171528.feam”,若要在代码中进行赋值,需要在Awake()中进行赋值。
组件讲解:
OnRespond事件:当识别成功后会调用的事件,当识别到该识别图之后要干什么。
3、实现样例
新建下面一个脚本,挂在Bear上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using BaiduARInternal;
public class ImageRecognition : MonoBehaviour
{
public GameObject go_Prefab;
private BaiduARImageRecognitionResult result;
private GameObject myGo = null;
private Transform parent;
private void Awake()
{
//获取BaiduARImageRecognitionResult组件
result = GetComponent<BaiduARImageRecognitionResult>();
//添加OnRespond事件
result.OnRespond.AddListener(OnRespond);
//寻找挂模型的父对象(Parent)
parent = GameObject.Find("Parent").transform;
}
/// <summary>
/// 当识别到识别图之后触发
/// </summary>
private void OnRespond()
{
//把挂模型的父对象(Parent)所有的子对象都隐藏起来
for (int i = 0; i < parent.childCount; i++)
{
parent.GetChild(i).gameObject.SetActive(false);
}
//假如该识别图的模型还没有挂在Parent上,就把模型挂上去
if (myGo == null)
{
myGo = Instantiate(go_Prefab, new Vector3(0, -15, 200), Quaternion.identity);
myGo.transform.eulerAngles = new Vector3(0, 180, 0);
myGo.transform.SetParent(parent);
}
//如果已经挂上去了(之前有识别过该图片),就激活该物体
else
{
myGo.SetActive(true);
}
}
}
可以在ARImageRecognition创建多个子物体(多张识别图)