如何不断获取触摸位置?

我有一个代码可以预测LateUpdate(). 它可以在 PC 和鼠标上完美运行。下面是使用鼠标时的代码:


    if(Input.GetMouseButton(0)){

        //get the rotation based on the start drag position compared to the current drag position

        zRotation = (Input.mousePosition.y - mouseStart) * (manager.data.sensitivity/15);

        zRotation = Mathf.Clamp(zRotation, -manager.data.maxAimRotation, manager.data.maxAimRotation);

    }

    //reset the rotation if the player is not aiming

    else if((int) zRotation != 0){

        if(zRotation > 0){

            zRotation --;

        }

        else{

            zRotation ++;

        }

    }

我现在想把它移植到 Android 上,所以我在玩Input.Touch. 我将上面的代码更改为以下内容:


 if (Input.touchCount > 0)

            {

                //get the rotation based on the start drag position compared to the current drag position

                zRotation = (Input.GetTouch(0).deltaPosition.y) * (manager.data.sensitivity / 15);

                zRotation = Mathf.Clamp(zRotation, -manager.data.maxAimRotation, manager.data.maxAimRotation);

            }

            //reset the rotation if the player is not aiming

            else if ((int)zRotation != 0)

            {

                if (zRotation > 0)

                {

                    zRotation--;

                }

                else

                {

                    zRotation++;

                }

            }

但是zRotation它不起作用,因为它在鼠标中起作用。它在每一帧后不断重置到起始位置。它几乎看起来像抖动。


我究竟做错了什么?


皈依舞
浏览 90回答 1
1回答

温温酱

我看到您正在使用的移动控件Input.GetTouch(0).deltaPosition.y。但是,为您提供上次更新deltaPosition位置与当前位置之间的差异。因此,假设您的应用程序以每秒 60 帧的速度运行,它将返回每 1/60 秒的距离。当然,这将是一个接近于零的数字,我相信这就是为什么它看起来总是返回起始位置的原因https://docs.unity3d.com/ScriptReference/Touch-deltaPosition.html您将不得不以类似于使用鼠标方法的方式进行操作。将变量设置为touchStartonTouchphase.Began并将其与touch.position.float touchStart = 0;if (Input.touchCount > 0)            {                if (Input.GetTouch(0).phase == TouchPhase.Began) touchStart = Input.GetTouch(0).position.y;                //get the rotation based on the start drag position compared to the current drag position                zRotation = (Input.GetTouch(0).position.y - touchStart) * (manager.data.sensitivity / 15);                zRotation = Mathf.Clamp(zRotation, -manager.data.maxAimRotation, manager.data.maxAimRotation);            }            //reset the rotation if the player is not aiming            else if ((int)zRotation != 0)            {                if (zRotation > 0)                {                    zRotation--;                }                else                {                    zRotation++;                }            }不过我还没有测试过,如果我错了,请纠正我!
打开App,查看更多内容
随时随地看视频慕课网APP