- Home /
Diagonal swipe issues on Android
Hi,
I'm using MNOGUE's code for detecting 8-way swipe (including diagonals, vertical and horizontal). The problem is, sometimes the diagonal swipes are not detected, and vertical or horizontal swipes happen instead. What can I do to this code to possibly improve the diagonal swipe response? Thanks in advance.
Here's the code:
private float fingerStartTime = 0.0f;
private Vector2 fingerStartPos = Vector2.zero;
private bool isSwipe = false;
private float minSwipeDist = 30.0f;
private float maxSwipeTime = 0.5f;
void Update()
{
if (Input.touchCount > 0 && Time.timeScale > 0.0f)
{
foreach (Touch touch in Input.touches)
{
switch (touch.phase)
{
case TouchPhase.Began:
/* this is a new touch */
isSwipe = true;
fingerStartTime = Time.time;
fingerStartPos = touch.position;
break;
case TouchPhase.Canceled:
/* The touch is being canceled */
isSwipe = false;
break;
case TouchPhase.Ended:
float gestureTime = Time.time - fingerStartTime;
float gestureDist = (touch.position - fingerStartPos).magnitude;
if (isSwipe && gestureTime < maxSwipeTime && gestureDist > minSwipeDist)
{
Vector2 direction = touch.position - fingerStartPos;
//Vector2 swipeType = Vector2.zero;
int swipeType = -1;
if (Mathf.Abs(direction.normalized.x) > 0.8)
{
if (Mathf.Sign(direction.x) > 0) swipeType = 0; // swipe right
else swipeType = 1; // swipe left
}
else if (Mathf.Abs(direction.normalized.y) > 0.8)
{
if (Mathf.Sign(direction.y) > 0) swipeType = 2; // swipe up
else swipeType = 3; // swipe down
}
else
{
// diagonal:
if (Mathf.Sign(direction.x) > 0)
{
if (Mathf.Sign(direction.y) > 0) swipeType = 4; // swipe diagonal up-right
else swipeType = 5; // swipe diagonal down-right
}
else
{
if (Mathf.Sign(direction.y) > 0) swipeType = 6; // swipe diagonal up-left
else swipeType = 7; // swipe diagonal down-left
}
}
switch(swipeType)
{
case 0: //right
break;
case 1: //left
break;
case 2: //up
break;
case 3: //down
case 4: //up right
case 5: //down right
break;
case 6: //up left
break;
case 7: //down left
break;
}
}
break;
}
}
}
}
Answer by tanoshimi · Aug 02, 2015 at 08:02 AM
Lower the sensitivity of the cardinal direction by reducing the 0.8 in lines 44 and 51 to, say, 0.65.
Thanks tanoshimi. Lowering the sensitivity of horizontal and vertical swipes was the right idea. But there was one small mistake with what you suggested. Lowering sensitivity would mean increasing the threshold value, not decreasing it.
I changed 0.8 to 0.9 and I think the diagonal swipes are better now. Thanks, I'll vote you up.
Your answer
Follow this Question
Related Questions
multi touch / swipe issues 5 Answers
Unity3d Get Cube Pressed On Mobile 1 Answer
Bug? Need to wait about 10 seconds to get back to normal 1 Answer
Stopping rotation at 90° and -90°/270°. 0 Answers
Touch - drag different objects 1 Answer