【发布时间】:2020-03-17 17:50:22
【问题描述】:
嘿,我正在开发一款 3d 统一的 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);
}
}
}
有谁知道问题或有其他解决方案让我按上述方式移动播放器
【问题讨论】:
-
为什么你总是在做
touchedPosMoved而不是只在TouchPhase.Moved?也可能使用ScreenToWorldPoint不是最好的选择..您可以直接使用输入差异乘以某个乘数...
标签: c# android unity3d controls touch