这是我尝试模拟滑动手势的代码,所以当我构建到移动设备时,我知道它会起作用。没有任何记录,我很困惑为什么它似乎不起作用。我希望它在我滑动 RTL
(从右到左)或 LTR
(从左到右)的控制台中打印出来。我看不出我做错了什么。
void Update()
{
if (Input.GetMouseButtonDown(0))
{
startPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
if (Input.GetMouseButtonUp(0))
{
endPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
if (startPosition != endPosition && startPosition != Vector3.zero && endPosition != Vector3.zero)
{
float deltaX = endPosition.x - startPosition.x;
float deltaY = endPosition.y - startPosition.y;
if ((deltaX > 5.0f || deltaX < -5.0f) && (deltaY >= -1.0f || deltaY <= 1.0f))
{
if (startPosition.x < endPosition.x)
{
print("LTR");
}
else
{
print("RTL");
}
}
startPosition = endPosition = Vector3.zero;
}
}
最佳答案
我可以在您的代码中发现一些问题。将 Vector3
与 ==
或 !=
进行比较不是一个好主意。大致比较就好了。您正在移动平台上使用 Input.GetMouseButtonDown
。
您需要使用 Input.touches
去做这个。循环它,将开始位置存储在 TouchPhase.Began
中然后是 TouchPhase.Ended
中的结束位置.然后,您可以使用这两个变量来确定手指移动的方向。
下面的代码在 TouchPhase.Moved
的帮助下检测滑动方向,即使手指尚未松开也是如此。 .您可以通过启用 detectSwipeOnlyAfterRelease
bool 变量来禁用它。您还可以修改 SWIPE_THRESHOLD
以提高灵敏度。
public class SwipeDetector : MonoBehaviour
{
private Vector2 fingerDown;
private Vector2 fingerUp;
public bool detectSwipeOnlyAfterRelease = false;
public float SWIPE_THRESHOLD = 20f;
// Update is called once per frame
void Update()
{
foreach (Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
fingerUp = touch.position;
fingerDown = touch.position;
}
//Detects Swipe while finger is still moving
if (touch.phase == TouchPhase.Moved)
{
if (!detectSwipeOnlyAfterRelease)
{
fingerDown = touch.position;
checkSwipe();
}
}
//Detects swipe after finger is released
if (touch.phase == TouchPhase.Ended)
{
fingerDown = touch.position;
checkSwipe();
}
}
}
void checkSwipe()
{
//Check if Vertical swipe
if (verticalMove() > SWIPE_THRESHOLD && verticalMove() > horizontalValMove())
{
//Debug.Log("Vertical");
if (fingerDown.y - fingerUp.y > 0)//up swipe
{
OnSwipeUp();
}
else if (fingerDown.y - fingerUp.y < 0)//Down swipe
{
OnSwipeDown();
}
fingerUp = fingerDown;
}
//Check if Horizontal swipe
else if (horizontalValMove() > SWIPE_THRESHOLD && horizontalValMove() > verticalMove())
{
//Debug.Log("Horizontal");
if (fingerDown.x - fingerUp.x > 0)//Right swipe
{
OnSwipeRight();
}
else if (fingerDown.x - fingerUp.x < 0)//Left swipe
{
OnSwipeLeft();
}
fingerUp = fingerDown;
}
//No Movement at-all
else
{
//Debug.Log("No Swipe!");
}
}
float verticalMove()
{
return Mathf.Abs(fingerDown.y - fingerUp.y);
}
float horizontalValMove()
{
return Mathf.Abs(fingerDown.x - fingerUp.x);
}
//////////////////////////////////CALLBACK FUNCTIONS/////////////////////////////
void OnSwipeUp()
{
Debug.Log("Swipe UP");
}
void OnSwipeDown()
{
Debug.Log("Swipe Down");
}
void OnSwipeLeft()
{
Debug.Log("Swipe Left");
}
void OnSwipeRight()
{
Debug.Log("Swipe Right");
}
}
关于c# - 检测滑动手势方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41491765/