| 在进行AR应用开发的过程中,配置了射线检测, 但每次点击屏幕,都会生成一个以上的GameObject主要原因是在Unity的MonoBehaviour脚本中,Updata()方法是按帧执行的,默认一秒是设置为60帧
 因此点击一次会响应多次结果
 只要在脚本中设置一个bool变量来监控Input.touchCount就可以控制单次点击响应一次结果
 这里使用的是AR射线检测的基础代码,
 具体代码:
 public class RaycastHitTest_1 : MonoBehaviour
{
    public GameObject defaultPrefab;
    private ARRaycastManager raycastManager;
    private List<ARRaycastHit> hits = new List<ARRaycastHit>();
    private GameObject box = null;
    private bool touching = false;
    
    void Start()
    {
        raycastManager = GetComponent<ARRaycastManager>();
    }
    
    void Update()
    {
        if (Input.touchCount == 0)
        {
            touching = false;
            return;
        }
        else if(touching == false)
        {
            
            Vector2 touchPosition = Input.GetTouch(0).position;
            
            if (raycastManager.Raycast(touchPosition, hits, TrackableType.PlaneWithinPolygon))
            {
                touching = true;
                Pose hitPose = hits[0].pose;
                Vector3 gamePosition = new Vector3(hitPose.position.x, hitPose.position.y + 0.1f, hitPose.position.z);
                box = Instantiate(defaultPrefab, hitPose.position, defaultPrefab.transform.rotation);
            }
        }
    }
}
 |