团结玩家用手指在x轴上移动是不起作用的



嘿,我正在开发一款三维统一的android游戏,重点是你是一个必须在x轴上移动的正方形。我希望玩家可以把手指放在他想放的地方,向左或向右滑动(仍然触摸显示器(,他开始触摸的位置和他现在所在的位置之间的距离应该向右或向左移动。当玩家没有触摸时,它不应该在x轴上移动。我这样做了,但我的代码有一个问题,当我松开手指,在没有左右移动的情况下再次触摸时,正方形会很快偏转到一边。当然,当手指不动的时候,方块就不应该动了。

更好地理解的图片

// 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);
}
}
}

有人知道这个问题吗?或者有其他解决方案可以让我如上所述移动玩家吗

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

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);
}
}
}

最新更新