Unity 沿 X 轴移动播放器

我正在尝试根据手指位置创建沿 x 轴的玩家移动。

我需要发生的事情:不是多点触控。我想要这样一个玩家可以放下一根手指并抓住那个位置。然后检查玩家是否在 x 轴上沿屏幕拖动手指,并根据他们从第一次触摸时拖动手指的位置向左或向右移动玩家。

因此,如果他们触摸屏幕并向左拖动:按速度向左移动,如果更改为向右拖动,则按速度向右移动。

任何帮助都是极好的。


慕少森
浏览 156回答 2
2回答

慕森卡

最简单的方法是存储第一个触摸位置,然后将 X 与该位置进行比较:public class PlayerMover : MonoBehaviour{&nbsp; &nbsp; /// Movement speed units per second&nbsp; &nbsp; [SerializeField]&nbsp; &nbsp; private float speed;&nbsp; &nbsp; /// X coordinate of the initial press&nbsp; &nbsp; // The '?' makes the float nullable&nbsp; &nbsp; private float? pressX;&nbsp; &nbsp; /// Called once every frame&nbsp; &nbsp; private void Update()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // If pressed with one finger&nbsp; &nbsp; &nbsp; &nbsp; if(Input.GetMouseButtonDown(0))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pressX = Input.touches[0].position.x;&nbsp; &nbsp; &nbsp; &nbsp; else if (Input.GetMouseButtonUp(0))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pressX = null;&nbsp; &nbsp; &nbsp; &nbsp; if(pressX != null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; float currentX = Input.touches[0].position.x;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // The finger of initial press is now left of the press position&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(currentX < pressX)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Move(-speed);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // The finger of initial press is now right of the press position&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else if(currentX > pressX)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Move(speed);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // else is not required as if you manage (somehow)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // move you finger back to initial X coordinate&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // you should just be staying still&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; `&nbsp; &nbsp; /// Moves the player&nbsp; &nbsp; private void Move(float velocity)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; transform.position += Vector3.right * velocity * Time.deltaTime;&nbsp; &nbsp; }}警告:此解决方案仅适用于具有可用触摸输入的设备(因为使用 Input.touches)。
打开App,查看更多内容
随时随地看视频慕课网APP