How to Double Click in Phaser 3

One of the things missing from a lot of modern frameworks is the ability to detect a double click. When you come down to it, a double click is simply 2 single clicks close together. All we really need to do is measure the time between clicks. We can do that by measuring the delta time.

class SceneMain extends Phaser.Scene {
    constructor() {
        super('SceneMain');
    }
    preload() {}
    create() {
        this.firstClickTime = 0;
        //add a listeners for when the pointer goes down
        this.input.on('pointerdown', this.onDown.bind(this));
    }
    getTime() {
        //make a new date object
        let d = new Date();
        //return the number of milliseconds since 1 January 1970 00:00:00.
        return d.getTime();
    }
    onDown() {
        //if the firstClickTime is 0 then
        //this we record the time and leave the function
        if (this.firstClickTime == 0) {
            this.firstClickTime = this.getTime();
            return;
        }
        //
        //get the elapsed time between clicks
        //
        let elapsed = this.getTime() - this.firstClickTime;
        //
        //if the time between clicks is less than 350 milliseconds
        //it is a doulble click
        //
        if (elapsed < 350) {
            console.log("double click");
        }
        //
        //reset the firstClickTime
        //
        this.firstClickTime = 0;
    }
    update() {}
}

Leave a Comment