Collision

To check for collision between two objects, you must first enable physics on both of them.

Then, in the source editor, we add collision check and keyboard controls to the box object:

"use strict";
window.Collision.state.menu = {
    create: function() {
        this.grass = mt.create("grass");
        this.box = mt.create("box_simple");

        //initializes the cursor keys
        this.cursors = this.game.input.keyboard.createCursorKeys();
    },

    update: function() {
        //changes the physics body velocity, depending on the key pressed; basic movement controls
        if (this.cursors.up.isDown) this.box.body.velocity.y = -150;
        else if (this.cursors.down.isDown) this.box.body.velocity.y = 150;
        else this.box.body.velocity.y = 0;

        if (this.cursors.right.isDown) this.box.body.velocity.x = 150;
        else if (this.cursors.left.isDown) this.box.body.velocity.x = -150;
        else this.box.body.velocity.x = 0;

        //collision check between two sprites
        //the game checks for collision ONLY between these two sprites
        //can also check between sprite vs group and group vs group
        this.game.physics.arcade.collide(this.grass, this.box);

    }
};

Full sample available here.

One thought on “Collision

Leave a Reply

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