我使用以下代码行来准确检测四个方向的滑动,但我不明白为什么它不起作用请帮助
void Update ()
{
if (Input.GetKey(KeyCode.Joystick1Button9))
Application.Quit();
Dictionary<int, Touch> touch = new Dictionary<int, Touch>();
foreach (Touch t in Input.touches)
{
Vector2 Direction = new Vector2(0,0);
switch (t.phase)
{
case TouchPhase.Began:
touch[t.fingerId] = t;
Swiped = false;
break;
case TouchPhase.Ended:
if (touch.ContainsKey(t.fingerId))
{
Direction = t.position - touch[t.fingerId].position;
Direction = Direction.normalized;
Swiped = true;
}
else
Swiped = false;
break;
default :
Swiped = false;
break;
}
if (Swiped)
{
if (Vector2.Dot(Direction,Vector2.up) > Mathf.Sqrt(1/2f))
{
GameObject.FindObjectOfType<Light>().color = Color.red ;
RandomObjects();
}
else if (Vector2.Dot(Direction, -1*Vector2.up) > Mathf.Sqrt(1/2f))
{
GameObject.FindObjectOfType<Light>().color = Color.green;
RandomObjects();
}
else if (Vector2.Dot(Direction, Vector2.right) > Mathf.Sqrt(1/2f))
{
GameObject.FindObjectOfType<Light>().color = Color.blue;
RandomObjects();
}
else if (Vector2.Dot(Direction,-1 * Vector2.right) > Mathf.Sqrt(1/2f))
{
GameObject.FindObjectOfType<Light>().color = Color.yellow;
RandomObjects();
}
}
}
}
正如所建议我停止使用Coroutine并在Update()方法中编写代码。
答案 0 :(得分:1)
您的代码中存在许多问题:
Input.GetTouch()
之后不能再次致电WaitForSeconds
。所以,它应该是这样的:
const float swipeThreshold = 100.0f;
IEnumerator SwipeInput(Action<Vector2> onSwipe)
{
Dictionary<int, Touch> activeTouches = new Dictionary<int, Touch>();
Dictionary<int, Vector3> activeButtons = new Dictionary<int, Vector3>();
while (true)
{
if (Input.touches.Length > 0)
foreach (Touch touch in Input.touches)
switch (touch.phase)
{
case TouchPhase.Began:
activeTouches[touch.fingerId] = touch;
break;
case TouchPhase.Ended:
if (activeTouches.ContainsKey(touch.fingerId))
{
Vector2 delta = touch.position - activeTouches[touch.fingerId].position;
if (delta.magnitude > swipeThreshold)
onSwipe(delta);
}
break;
}
else
for (int i = 0; i <= 2; ++i)
{
if (Input.GetMouseButtonDown(i))
activeButtons[i] = Input.mousePosition;
else if (Input.GetMouseButtonUp(i) && activeButtons.ContainsKey(i))
{
Vector2 delta = Input.mousePosition - activeButtons[i];
if (delta.magnitude > swipeThreshold)
onSwipe(delta);
}
}
yield return new WaitForFixedUpdate();
}
}
P.S。协同程序看起来很酷。但是不要将它用于你能想到的一切。或者你最终会争取同步它们。只有在你真正需要它们时才使用它们。即使用它们时会产生更清晰,紧凑或优雅的代码。例如,手势检测并非如此。