2017-11-10 114 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 
}