目前ARCore的最新版本是1.2。Unity SDK还没提供直接隐藏显示网格的接口。本文根据官方的案例进行修改。
控制网格线显示的类文件是TrackedPlaneVisualizer,在Update()函数中,控制网格线显示的代码是:
1 |
m_MeshRenderer.enabled = true; |
把这句话改为
1 |
m_MeshRenderer.enabled = false; |
则不管怎么识别,一直保持隐藏网格线。
现在需要做到的是,通过点击按钮,实时隐藏或显示网格线。
在官方案例中,planes是作为一个GameObject的,在每次识别到新的平面就会创建一个plane的GameObject,并且使用TrackedPlaneVisualizer.cs作为script Component来控制网格线的渲染和可视化。要在每次创建新plane的时候,将它存储到一个GameObject数组里面,再循环遍历这个数组,执行TrackedPlaneVisualizer中定义的一个控制显示和隐藏的函数。
添加点击事件
在HelloARController.cs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
private bool hide_show_plane = true; private List<GameObject> m_NewPlanes_visible = new List<GameObject>(); // 把这个函数绑定到按钮点击事件中 public void Hide_pointCloud() { if (hide_show_plane) { hide_show_plane = false; } else { hide_show_plane = true; } } |
在该脚本的Update函数中修改,下面代码只贴出Update函数的部分,其他代码与原Update代码一样, 找出相应的地方进行修改即可:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Iterate over planes found in this frame and instantiate corresponding GameObjects to visualize them. Session.GetTrackables<TrackedPlane>(m_NewPlanes, TrackableQueryFilter.New); for (int i = 0; i < m_NewPlanes.Count; i++) { // Instantiate a plane visualization prefab and set it to track the new plane. The transform is set to // the origin with an identity rotation since the mesh for our prefab is updated in Unity World // coordinates. GameObject planeObject = Instantiate(TrackedPlanePrefab, Vector3.zero, Quaternion.identity, transform); // 把plane GameObject 放入数组 m_NewPlanes_visible.Add(planeObject); planeObject.GetComponent<TrackedPlaneVisualizer>().Initialize(m_NewPlanes[i], true); } // 遍历数组,调用函数Hide_pointCloud,传递hide_show_plane参数 for (int i = 0; i < m_NewPlanes_visible.Count; i++) { // call the method on TrackedPlaneVisualizer.cs m_NewPlanes_visible[i].SendMessage("Hide_pointCloud", hide_show_plane); } |
控制网格隐藏与显示
在TrackedPlaneVisualizer.cs :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
private bool isShow = true; // just change one line in Update method public void Update() { if (m_TrackedPlane == null) { return; } else if (m_TrackedPlane.SubsumedBy != null) { Destroy(gameObject); return; } else if (m_TrackedPlane.TrackingState != TrackingState.Tracking) { m_MeshRenderer.enabled = false; return; } // 根据传递的参数控制网格的显示或者隐藏 m_MeshRenderer.enabled = isShow; _UpdateMeshIfNeeded(); } // 调用的函数 public void Hide_pointCloud(bool hide_show_plane) { isShow = hide_show_plane; m_MeshRenderer.enabled = hide_show_plane; // update the pointcloud Update(); } |
到这里基本修改完毕了。
最终效果
© 著作权归作者所有
文章评论(0)