在进行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;//用于监测触碰次数
// Start is called before the first frame update
void Start()
{
raycastManager = GetComponent<ARRaycastManager>();
}
// Update is called once per frame
void Update()
{
if (Input.touchCount == 0)
{
touching = false;
return;
}
else if(touching == false)
{
//如果触屏次数为0,则不进行操作
Vector2 touchPosition = Input.GetTouch(0).position;
//射线检测命中trackableTypes中的可跟踪项,则为True
if (raycastManager.Raycast(touchPosition, hits, TrackableType.PlaneWithinPolygon))
{
touching = true;
Pose hitPose = hits[0].pose;//获取该帧第一次命中的pose
Vector3 gamePosition = new Vector3(hitPose.position.x, hitPose.position.y + 0.1f, hitPose.position.z);
box = Instantiate(defaultPrefab, hitPose.position, defaultPrefab.transform.rotation);
}
}
}
}