[英]Unity Moving Player along X-axis
我正在嘗試根據手指位置創建沿x軸的玩家移動。
我需要發生的事情:不是多點觸控。 我想要它,所以玩家可以放下一根手指並抓住那個位置。 然后檢查玩家是否在x軸上沿着屏幕拖動手指並根據他們從第一次觸摸拖動手指的位置向左或向右移動玩家。
因此,如果他們觸摸屏幕並向左拖動:向左移動速度,如果它改變為向右拖動,則向右移動。
任何幫助都是極好的。
最簡單的方法是存儲第一個觸摸位置,然后將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)。
使用此答案中提供的代碼@programmer: 檢測滑動手勢方向
您可以輕松檢測您正在滑動/拖動的方向。 替換調試
void OnSwipeLeft()
{
Debug.Log("Swipe Left");
}
void OnSwipeRight()
{
Debug.Log("Swipe Right");
}
使用可以移動角色的功能。 如果您使用RigidBody移動角色,可以使用https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html 。 如果它是普通對象,您可以通過調整transform.position
來移動它。
如果您需要有關如何移動剛體\\普通對象的更多信息,請告訴我您的游戲類型以及有關如何設置播放器的更多詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.