Skip to content

Instantly share code, notes, and snippets.

@netgfx
Forked from photonstorm/PointerMonitor.js
Created December 5, 2018 12:22
Show Gist options
  • Save netgfx/3149c16ad445f82b34b0153d70e6210e to your computer and use it in GitHub Desktop.
Save netgfx/3149c16ad445f82b34b0153d70e6210e 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