【问题标题】:unity player moving on the x axis with the finger does not work用手指在 x 轴上移动的统一播放器不起作用
【发布时间】:2020-03-17 17:50:22
【问题描述】:

嘿,我正在开发一款 3d 统一的 android 游戏,重点是你是一个正方形,你必须在 x 轴上移动。我希望玩家可以将手指放在他想要的任何地方并向左或向右滑动(仍然触摸显示屏),并且他开始触摸的位置与他现在所在的位置之间的距离应该向右或向左移动。当玩家不接触时,它不应该在 x 轴上移动。我这样做了,但是当我松开手指并再次触摸而不向右或向左移动时,我的代码出现问题,正方形非常快速地偏向一侧。当然,当手指不移动时,方块不应该移动。

Picture for better understand

// My Code
public class PlayerMovement : MonoBehaviour
{
    void FixedUpdate()
    {
        // move the player constantly forward
        transform.position += Vector3.forward * Time.deltaTime * speed;

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

            // the current finger position
            touchedPosMoved = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 10));

            switch (touch.phase)
            {
                case TouchPhase.Began:
                    // get finger position when touch start
                    touchedPosBegan = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 10));

                    startX = transform.position.x;
                    break;

                case TouchPhase.Moved:
                    // claculate the distance between start and curent position of the finger
                    differenz = Mathf.Abs(touchedPosBegan.x - touchedPosMoved.x);

                    if (touchedPosBegan.x > touchedPosMoved.x)
                    {
                        differenz = differenz * -1;
                    }
                    break;
            }


            // Move player at the X-axis
            Vector3 idk = new Vector3((startX + differenz) * 8, transform.position.y, transform.position.z);
            gameObjectStart = new Vector3(startX, transform.position.y, transform.position.z);
            transform.position = Vector3.Lerp(gameObjectStart, idk, Time.deltaTime * 2);
        }
    }
}

有谁知道问题或有其他解决方案让我按上述方式移动播放器

【问题讨论】:

  • 为什么你总是在做touchedPosMoved 而不是只在TouchPhase.Moved?也可能使用ScreenToWorldPoint不是最好的选择..您可以直接使用输入差异乘以某个乘数...

标签: c# android unity3d controls touch


【解决方案1】:

在这里我找到了没有这些问题的更好的代码我希望这可以帮助其他程序员;)

   private void FixedUpdate()
{
    transform.position += Vector3.forward * Time.deltaTime * speed;

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

        if (touch.phase == TouchPhase.Moved)
        {
            transform.position = new Vector3(
                transform.position.x + touch.deltaPosition.x * multiplier,
            transform.position.y,
            transform.position.z + touch.deltaPosition.y * multiplier);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 2020-01-13
    • 1970-01-01
    相关资源
    最近更新 更多