用手指在x轴上移动的社区播放器不起作用

问题描述 投票:0回答:1

[嘿,我正在开发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);
        }
    }
}

是否有人知道问题或如上所述有其他解决办法来移动播放器

c# android unity3d controls touch
1个回答
0
投票

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

   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);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.