Skip to content

Instantly share code, notes, and snippets.

@photonstorm
Created December 3, 2018 16:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save photonstorm/cd72279899e4f190efdda05f59529c4e to your computer and use it in GitHub Desktop.
Save photonstorm/cd72279899e4f190efdda05f59529c4e to your computer and use it in GitHub Desktop.
class PointerMonitor
{
constructor (scene, pointer, swipeThreshold = 100, swipeDuration = 500)
{
// The current Scene
this.scene = scene;
// The Pointer we're monitoring for swipes
this.pointer = pointer;
// They must move this distance on a single axis during the swipe
this.swipeThreshold = swipeThreshold;
// They cannot move more than 80% in the opposite axis during the swipe
this.swipeAxisThreshold = swipeThreshold * 0.8;
// The swipe must complete within this ms value, or less
this.swipeDuration = swipeDuration;
this.start();
}
start ()
{
this.scene.input.on('pointerup', this.onUp, this);
}
stop ()
{
this.scene.input.off('pointerup', this.onUp, this);
}
onUp (pointer)
{
if (pointer !== this.pointer)
{
return;
}
const distanceX = pointer.getDistanceX();
const distanceY = pointer.getDistanceY();
const horizontal = (distanceX > distanceY);
if (pointer.getDuration() < this.swipeDuration)
{
if (horizontal && distanceX > this.swipeThreshold && distanceY < this.swipeAxisThreshold)
{
// Horizontal Swipe
if (pointer.velocity.x < 0)
{
this.scene.input.emit('swipeleft', this.pointer);
}
else
{
this.scene.input.emit('swiperight', this.pointer);
}
}
else if (!horizontal && distanceY > this.swipeThreshold && distanceX < this.swipeAxisThreshold)
{
// Vertical Swipe
if (pointer.velocity.y < 0)
{
this.scene.input.emit('swipeup', this.pointer);
}
else
{
this.scene.input.emit('swipedown', this.pointer);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment