Skip to content

Instantly share code, notes, and snippets.

@mattheworiordan
Created July 20, 2011 10:24
Show Gist options
  • Save mattheworiordan/1094727 to your computer and use it in GitHub Desktop.
Save mattheworiordan/1094727 to your computer and use it in GitHub Desktop.
swipe detection example for Titanium
var movementHistory = {
pointAndTimeHistory: [],
set: function(point) {
// add this point into the point and time history for velocity calculations based on time & distance
this.pointAndTimeHistory.push({
time: new Date().getTime(),
x: point.x,
y: point.y
});
// trim history older than 300ms ago
while ( (this.pointAndTimeHistory.length > 0) && ( (this.pointAndTimeHistory[0].time+300) < (new Date()).getTime() ) ) {
this.pointAndTimeHistory.shift();
}
// get average horizonal velocity based on oldest co-ordinate and newest co-ordinate
if (this.pointAndTimeHistory.length) {
this.xVelocity = (point.x - this.pointAndTimeHistory[0].x) / (new Date() - this.pointAndTimeHistory[0].time);
if (isNaN(this.xVelocity)) { this.xVelocity = 0; } // protect against NaN
this.yVelocity = (point.y - this.pointAndTimeHistory[0].y) / (new Date() - this.pointAndTimeHistory[0].time);
if (isNaN(this.yVelocity)) { this.yVelocity = 0; } // protect against NaN
} else {
this.xVelocity = 0;
this.yVelocity = 0;
}
// store the current position
this.x = point.x;
this.y = point.y;
}
};
view.addEventListener('touchstart', function(e) {
movementHistory.set(e.globalPoint);
});
view.addEventListener('touchmove', function(e) {
movementHistory.set(e.globalPoint);
if (Math.abs(movementHistory.xVelocity) > Math.abs(movementHistory.yVelocity)) {
if (Math.abs(movementHistory.xVelocity) > 1) {
// horizontal swipe as user has gestured quickly but not lifted their finger
// if x > 0 then swipe is left to right
}
} else {
if (Math.abs(movementHistory.yVelocity) > 1) {
// vertical swipe as user has gestured quickly but not lifted their finger
// if y > 0 then vertically down
}
}
});
view.addEventListener('touchend', function(e) {
movementHistory.set(e.globalPoint);
if (Math.abs(movementHistory.xVelocity) > Math.abs(movementHistory.yVelocity)) {
if (Math.abs(movementHistory.xVelocity) > 0.25) {
// horizontal swipe as user has gestured and lifted their finger
}
} else {
if (Math.abs(movementHistory.yVelocity) > 0.25) {
// vertical swipe as user has gestured and lifted their finger
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment