Overlap Without Physics

Checking overlap between two sprites can be done without enabling physics for them.

Code:

"use strict";
window.Overlap.state.menu = {
    create: function() {
        //create both objects and allow them to be dragged across the map
        this.box = mt.create("box_simple");
        this.box.inputEnabled = true;
        this.box.input.enableDrag();

        this.grass = mt.create("grass");
        this.grass.inputEnabled = true;
        this.grass.input.enableDrag();

        this.text = mt.create("Text");
    },

    update: function() {
        //checks, if the overlap function returns true and acts accordingly
        if (this.checkOverlap(this.box, this.grass)) {
            this.text.setText('Yay!');
        } else {
            this.text.setText('');
        }
    },

    //gets bounds form both sprites and returns true, if they intersect each other
    checkOverlap: function(spriteA, spriteB) {

        var boundsA = spriteA.getBounds();
        var boundsB = spriteB.getBounds();

        return Phaser.Rectangle.intersects(boundsA, boundsB);

    }
};

Mouse drag any sprite over the other.

Full sample available here.

2 comments on “Overlap Without Physics

Leave a Reply

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