【问题标题】:How to move right and left with touch?如何通过触摸左右移动?
【发布时间】:2019-06-23 20:41:48
【问题描述】:

我想从整个屏幕向左和向右移动角色,如果我从任何地方向左或向右移动,它只需要移动我现在拥有的数量 = 1.5f

我有这个代码并且工作完美,但它只适用于鼠标而不是触摸屏:

if (!isMoving && Input.GetMouseButtonDown(0))
{
    desiredPos = transform.position + Vector3.right * 1.52f;
    isMoving = true;
}

if (!isMoving && Input.GetMouseButtonDown(1))
{
    desiredPos = transform.position - Vector3.right * 1.52f;
    isMoving = true;
}

if (isMoving)
{
    transform.position = Vector3.MoveTowards(transform.position, desiredPos, moveSpeed * Time.deltaTime);

    // this == is true if the difference between both
    // vectors is smaller than 0.00001
    if (transform.position == desiredPos)
    {
        isMoving = false;

        // So in order to eliminate any remaining difference
        // make sure to set it to the correct target position
        transform.position = desiredPos;
    }
}

我试图实现这段代码,但它不起作用

private void Update()
{
    timer += Time.deltaTime;

    int i = 0;
    //loop over every touch found
    while (i < Input.touchCount)
    {
        if (!isMoving && Input.GetTouch(i).position.x > ScreenWidth / 2)
        {
            //move right
            desiredPos = transform.position + Vector3.right * 1.52f;
            isMoving = true;
        }
        if (!isMoving && Input.GetTouch(i).position.x < ScreenWidth / 2)
        {
            //move left
            desiredPos = transform.position - Vector3.right * 1.52f;
            isMoving = true;
        }
        ++i;
    }


    if (isMoving)
    {
        transform.position = Vector3.MoveTowards(transform.position, desiredPos, moveSpeed * Time.deltaTime);

        // this == is true if the difference between both
        // vectors is smaller than 0.00001
        if (transform.position == desiredPos)
        {
            isMoving = false;

            // So in order to eliminate any remaining difference
            // make sure to set it to the correct target position
            transform.position = desiredPos;
        }
    }
}

第二个代码将字符向左或向右移动太多,我需要像在第一个代码中一样移动,但触摸向左或向右滑动。

我想要这样的东西精确移动 1.5f

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    要与GetMouseButtonDown 表现相同,您还需要检查触摸的短语:

    Input.GetTouch(i).phrase == TouchPhase.Began
    

    【讨论】:

    • 如何在我的第一个代码中实现这一点,请帮助我的示例
    • 由于 OP 是 Touch 输入的新手,因此在检查任何给定 Touch 的状态之前添加有关检查 Touches 的注释可能会有所帮助。
    猜你喜欢
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    相关资源
    最近更新 更多