简体   繁体   English

如何在 Unity 3D 上正确配置触摸?

[英]How do I properly configure touch on Unity 3D?

I'm making a game on Unity3D.我正在 Unity3D 上制作游戏。 The cube, as shown in the attached photo, should move to a certain position, I achieved this, but there was a problem when I click on the screen, it moves several positions at once, I tested this situation with Debug.如图所示,立方体应该移动到某个position,我实现了这个,但是当我点击屏幕时出现问题,它一次移动了几个位置,我用Debug测试了这种情况。 Log (I also attached the photo), and as you can see, with one click, the function is triggered several times, how to fix it?日志(我还附上了照片),如您所见,一键触发function多次,如何解决?

PS Also could advise how to add smoothness of movement of the cube, in a certain coordinate, tried through transform.forward, but couldn't figure out how to stop it at the right coordinate. PS还可以建议如何在某个坐标中添加立方体运动的平滑度,尝试通过transform.forward,但无法弄清楚如何在正确的坐标处停止它。

The cube's position立方体的 position

The Message Debug.Log消息调试日志

private void Update()
{
    CubePosUp_Z = transform.position.z - 0.7f;
    CubePosDown_Z = transform.position.z + 0.7f;
    if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);

        if (touch.position.y > Screen.height / 2)
        {
            tempUp = 1;
            tempDown = 0;
        }
        else
        {
            tempUp = 0;
            tempDown = 1;
        }

        if (tempUp == 1 && tempDown == 0)
        {
            UpTran();
        }
        else if (tempUp == 0 && tempDown == 1)
        {
            DownTran();
        }
    }
}

void UpTran()
{
    Debug.Log("Up");

    if (CubePosUp_Z <= -1.4)
    {
        transform.Translate(0, 0, 0, Space.World);
    }
    else if (CubePosUp_Z > -1.4)
    {
        transform.Translate(0, 0, -0.14f, Space.World);
    }
}
void DownTran()
{
    if (CubePosDown_Z >= 1.4)
    {
        transform.Translate(0, 0, 0, Space.World);
    }
    else if (CubePosDown_Z < 1.4)
    {
        transform.Translate(0, 0, 0.14f, Space.World);
    }
}

@TheHotboll Here's your solution:- @TheHotboll 这是您的解决方案:-

[SerializeField] float touchForce = 2f;

void Update ()
{
    if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch (0);

        if (touch.phase == TouchPhase.Moved)
        {
            transform.Translate (0f, 0f, touch.deltaPosition.x * touchForce * Time.deltaTime, Space.World);
        }
    }
}

First in the Update () function we check if we are actually swiping or just touching.首先在Update () function 中,我们检查我们是否真的在滑动或只是触摸。 If we are swiping, then we move the transform using transform.Translate () function on the World Space .如果我们正在滑动,那么我们在World Space上使用transform.Translate () function 移动变换。 You can also add conditions and check for touch.deltaPosition.x .您还可以添加条件并检查touch.deltaPosition.x This will work smoothly.这将顺利进行。 Just try it out.试试看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM