Unity开发(Android):控制设备单次触碰单次响应

在进行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);
            }
        }
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值