2 回答

TA貢獻1806條經驗 獲得超8個贊
最簡單的方法是存儲第一個觸摸位置,然后將 X 與該位置進行比較:
public class PlayerMover : MonoBehaviour
{
/// Movement speed units per second
[SerializeField]
private float speed;
/// X coordinate of the initial press
// The '?' makes the float nullable
private float? pressX;
/// Called once every frame
private void Update()
{
// If pressed with one finger
if(Input.GetMouseButtonDown(0))
pressX = Input.touches[0].position.x;
else if (Input.GetMouseButtonUp(0))
pressX = null;
if(pressX != null)
{
float currentX = Input.touches[0].position.x;
// The finger of initial press is now left of the press position
if(currentX < pressX)
Move(-speed);
// The finger of initial press is now right of the press position
else if(currentX > pressX)
Move(speed);
// else is not required as if you manage (somehow)
// move you finger back to initial X coordinate
// you should just be staying still
}
}
`
/// Moves the player
private void Move(float velocity)
{
transform.position += Vector3.right * velocity * Time.deltaTime;
}
}
警告:此解決方案僅適用于具有可用觸摸輸入的設備(因為使用 Input.touches)。
- 2 回答
- 0 關注
- 179 瀏覽
添加回答
舉報