Your first Phaser 3 + Matter.js physics example
Talking about Game development, HTML5, Javascript and Phaser.
Learn cross platform HTML5 game development
Check my Gumroad page for commented source code, games and books.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | // to be executed once the window loads window.onload = function (){ // game configuration object var gameConfig = { // render type type: Phaser.CANVAS, // game width, in pixels width: 640, // game height, in pixels height: 480, // game background color backgroundColor: "#000044" , // physics settings physics: { // we are using matter.js engine default : "matter" }, // array with all game scenes, just one: playGame scene: [playGame] }; // game constructor var game = new Phaser.Game(gameConfig); } // playGame Class var playGame = new Phaser.Class({ // it extends Phaser.Scene Extends: Phaser.Scene, // scene initialization initialize: // constructor function playGame(){ // calling the scene, assigning it "PlayGame" key Phaser.Scene.call( this , {key: "PlayGame" }); }, // function to be executed when the scene is loading preload: function (){ // loading crate image this .load.image( "crate" , "crate.png" ); }, // function to be executed once the scene has been created create: function (){ // setting Matter world bounds this .matter.world.setBounds(0, -200, game.config.width, game.config.height + 200); // waiting for user input this .input.on( "pointerdown" , function (pointer){ // getting Matter bodies under the pointer var bodiesUnderPointer = Phaser.Physics.Matter.Matter.Query.point( this .matter.world.localWorld.bodies, pointer); // if there isn't any body under the pointer... if (bodiesUnderPointer.length == 0){ // create a crate this .matter.add.sprite(pointer.x, pointer.y, "crate" ); } // this is where I wanted to remove the crate. Unfortunately I did not find a quick way to delete the Sprite // bound to a Matter body, so I am setting it to invisible, then remove the body. else { bodiesUnderPointer[0].gameObject.visible = false ; this .matter.world.remove(bodiesUnderPointer[0]) } }, this ); } }); |
Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.