Skip to content

Instantly share code, notes, and snippets.

@Durss
Last active September 21, 2024 15:20
Show Gist options
  • Save Durss/4d78fb1e0cf410932e9d0d036a4577cd to your computer and use it in GitHub Desktop.
Save Durss/4d78fb1e0cf410932e9d0d036a4577cd to your computer and use it in GitHub Desktop.
Simple Touch sequence detector
export default class TouchDetector {
private startPos = {x:0, y:0};
private endPos = {x:0, y:0};
private sequence = [];
//0=Right 1=Down 2=Left 3=Top
private watchedSequence = [3,3,1,1,2,0,2,0];//Konami
constructor() {
super();
this.initialize();
}
private initialize():void {
document.addEventListener("mousedown", (e)=>this.onTouchStart(e));
document.addEventListener("mousemove", (e)=>this.onTouchMove(e));
document.addEventListener("mouseup", (e)=>this.onTouchEnd());
document.addEventListener("touchstart", (e)=>this.onTouchStart(e));
document.addEventListener("touchmove", (e)=>this.onTouchMove(e));
document.addEventListener("touchend", (e)=>this.onTouchEnd());
}
private onTouchStart(e:TouchEvent|MouseEvent):void {
let pos = {x:0, y:0};
if(e instanceof TouchEvent) {
let t = <TouchEvent>e;
pos.x = t.touches[0].clientX;
pos.y = t.touches[0].clientY;
}else{
pos.x = e.clientX;
pos.y = e.clientY;
}
this.startPos = pos;
}
private onTouchMove(e:TouchEvent|MouseEvent):void {
let pos = {x:0, y:0};
if(e instanceof TouchEvent) {
let t = <TouchEvent>e;
pos.x = t.touches[0].clientX;
pos.y = t.touches[0].clientY;
}else{
pos.x = e.clientX;
pos.y = e.clientY;
}
this.endPos = pos;
}
private onTouchEnd():void {
let a = Math.atan2((this.endPos.y - this.startPos.y), (this.endPos.x - this.startPos.x));
if(a < 0) a += Math.PI *2;
a += Math.PI/2/2;//Offset by a 8th of angle counter clockwise
a = Math.floor(a / (Math.PI/2)) * (Math.PI/2);
let id = 0;
if(a == 0) id = 0;//Right
if(a == Math.PI/2) id = 1;//Down
if(a == Math.PI) id = 2;//Left
if(a == (3*Math.PI)/2) id = 3;//Top
this.sequence.push(id);
if(this.sequence.length > 20) {
this.sequence.shift();
}
let index = 0;
for (let i = 0; i < this.sequence.length; i++) {
const id = this.sequence[i];
if(id == this.watchedSequence[index]) index ++;
if(index == this.watchedSequence.length) {
this.sequence = [];
console.log("SEQUENCE DETECTED !");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment