Ive been looking around for a script that will detect horizontal swipe gestures. I have found a few examples but they dont work. If someone can post this it would be greatly appreciated.
Here’s some code I threw together the other day to answer a similar question.
I’m sure it will need to be altered, but it’s a good start.
It works surprisingly well (but not great) when I do an iPad build.
Note:
This is just an example script intended to demonstrate the basic concept.
Here’s the idea:
- define a speed threshold: the minimum speed that determines a swipe
- each frame that has touchCount == 1, check if the speed is greater than the threshold
- if it is (and it wasn’t the last frame) store the start position
- if it is not (and it was the last frame) store end position and/or do stuff (swipe is complete)
Here’s some tested exactly twice code:
var swipeThresh : float = 1.2;
var swipeStart : Vector2 = Vector2.zero;
var swipeEnd : Vector2 = Vector2.zero;
var swipeWasActive : boolean = false;
function Update ()
{
if ( Input.touchCount == 1 ) {
processSwipe();
}
}
function OnGUI ()
{
processSwipe();
drawStartBox();
drawEndBox();
}
function processSwipe ()
{
if ( Input.touchCount != 1 ) {
return;
}
var theTouch : Touch = Input.touches[0];
/* skip the frame if deltaPosition is zero */
if ( theTouch.deltaPosition == Vector2.zero ) {
return;
}
var speedVec : Vector2 = theTouch.deltaPosition * theTouch.deltaTime;
var theSpeed : float = speedVec.magnitude;
var swipeIsActive : boolean = ( theSpeed > swipeThresh );
if ( swipeIsActive ) {
if ( ! swipeWasActive ) {
swipeStart = theTouch.position;
}
}
else {
if ( swipeWasActive ) {
swipeEnd = theTouch.position;
Debug.Log("Swipe Complete");
}
}
swipeWasActive = swipeIsActive;
}
function drawStartBox ()
{
if ( swipeStart == Vector2.zero ) {
return;
}
/* don't forget to invert the y-coordinate */
var theY = Screen.height - swipeStart.y;
var theX = swipeStart.x;
var theRect : Rect = Rect(theX, theY, 140, 40);
GUI.Label(theRect, "Start");
}
function drawEndBox ()
{
if ( swipeEnd == Vector2.zero ) {
return;
}
/* don't forget to invert the y-coordinate */
var theY = Screen.height - swipeEnd.y;
var theX = swipeEnd.x;
var theRect : Rect = Rect(theX, theY, 140, 40);
GUI.Label(theRect, "End");
}
I just gave this a try and it works surprisingly well…
I used a speed threshhold of 1.2, which can be adjusted in the Inspector.
Hope this helps!