2017-11-10 56 views
1

使用ARKit我可以点击表面以在此处放置3D对象。我也可以移动手指,从而沿着表面移动物体。ARKit - 无需触摸屏幕即可放置对象

如何让物体自动出现并粘贴到相机前面,而无需触摸屏幕?

这里是用手指轻敲将3D对象的示例脚本:

using System; 
using System.Collections.Generic; 

namespace UnityEngine.XR.iOS 
{ 
    public class UnityARHitTestExample : MonoBehaviour 
    { 
     public Transform m_HitTransform; 

     bool HitTestWithResultType (ARPoint point, ARHitTestResultType resultTypes) 
     { 
      List<ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest (point, resultTypes); 
      if (hitResults.Count > 0) { 
       foreach (var hitResult in hitResults) { 
        Debug.Log ("Got hit!"); 
        m_HitTransform.position = UnityARMatrixOps.GetPosition (hitResult.worldTransform); 
        m_HitTransform.rotation = UnityARMatrixOps.GetRotation (hitResult.worldTransform); 
        Debug.Log (string.Format ("x:{0:0.######} y:{1:0.######} z:{2:0.######}", m_HitTransform.position.x, m_HitTransform.position.y, m_HitTransform.position.z)); 
        return true; 
       } 
      } 
      return false; 
     } 

     // Update is called once per frame 
     void Update() { 
      if (Input.touchCount > 0 && m_HitTransform != null) 
      { 
       var touch = Input.GetTouch(0); 
       if (touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved) 
       { 
        var screenPosition = Camera.main.ScreenToViewportPoint(touch.position); 
        ARPoint point = new ARPoint { 
         x = screenPosition.x, 
         y = screenPosition.y 
        }; 

        // prioritize reults types 
        ARHitTestResultType[] resultTypes = { 
         ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent, 
         // if you want to use infinite planes use this: 
         //ARHitTestResultType.ARHitTestResultTypeExistingPlane, 
         ARHitTestResultType.ARHitTestResultTypeHorizontalPlane, 
         ARHitTestResultType.ARHitTestResultTypeFeaturePoint 
        }; 

        foreach (ARHitTestResultType resultType in resultTypes) 
        { 
         if (HitTestWithResultType (point, resultType)) 
         { 
          return; 
         } 
        } 
       } 
      } 
     } 


    } 
} 

回答

0

我已经做了在Objective-C类似的东西,所以希望我能和你团结例子帮助。

我的逻辑基本上是使用一个水龙头放置物体是基于hitTest函数,并提供一个从触摸位置检索的点。所以我只是在屏幕中心以编程方式创建了一个CGPoint,并使用这一点运行hitTest函数。如果它挂在计时器上,并且当返回的对象被添加到那里时。

CGPoint point = CGPointMake(self.sceneView.frame.size.width/2, self.sceneView.frame.size.height/2); //Get a point at the middle of the screen 
NSArray <ARHitTestResult *> *hitResults = [_sceneView hitTest:point types:ARHitTestResultTypeFeaturePoint]; //Try to do a AR Hit Test on this point 
if ([hitResults count] != 0) { //If have any results 
    //Perform desired operation 
}