Faking a Swipe in Phaser

One of the advantages native programs like Java for Android or Swift for IOS has over web languages like HTML5 is having built-in detection for detecting swiping. But with a little bit of coding, we can detect the actions of a swipe. For that, we need to break down the action of a swipe

  1. The user touches the phone (mouseDown)
  2. The user moves a finger across the phone
  3. The user lifts their finger(mouseUp)

Example

Code

var StateMain = {
    preload: function() {},
    create: function() {
    	//
    	//
    	//
        game.input.onUp.add(this.mouseUp, this);
        game.input.onDown.add(this.mouseDown, this);
        //
        //
        this.text1 = game.add.text(game.world.centerX, game.world.centerY, "swipe left or right!");
        this.text1.fill = "#ffffff";
        this.text1.anchor.set(0.5, 0.5);
    },
    mouseDown: function() {
    	//set the mouseIsDown to true
        this.mouseIsDown = true;
        //
        //
        //record the place the mouse started
        //
        //
        this.startX = game.input.x;
    },
    mouseUp: function() {
        this.mouseIsDown = false;
    },
    swipeDone: function() {
        //get the ending point
        var endX = game.input.x;
        //
        //
        //check the start point against the end point
        //
        //
        if (endX < this.startX) {
            //swipe left
            this.text1.text = "Swiped left";
        } else {
            //swipe right
            this.text1.text = "Swiped right";
        }
    },
    update: function() {
        if (this.mouseIsDown == true) {
        	//get the distance between the start and end point
            var distX = Math.abs(game.input.x - this.startX);
            //if the distance is greater than 50 pixels then a swipe has happened
            if (distX > 50) {
                this.swipeDone();
            }
        }
    }
}

 
Source Code Available in the FILE VAULT!

Leave a Reply

Your email address will not be published. Required fields are marked *