Phaser 自帶的Arcade雖然易用,但複雜的物理碰撞明顯就不夠用了,因而Matter等物理引擎仍是不得不學的,如下是Matter物理體碰撞的一個插件,它省去了咱們判別兩個物理體相撞後哪一個是gameObjectA和gameObjectB,實在是好用又省心,特推薦以下:javascript
引入插件:java
const config = { // ... physics: { default: "matter" }, // Install the scene plugin plugins: { scene: [ { plugin: PhaserMatterCollisionPlugin, // The plugin class key: "matterCollision", // Where to store in Scene.Systems, e.g. scene.sys.matterCollision mapping: "matterCollision" // Where to store in the Scene, e.g. scene.matterCollision } ] } }; const game = new Phaser.Game(config);
識別二個相撞體npm
const player = this.matter.add.sprite(0, 0, "player"); const trapDoor = this.matter.add.image(200, 0, "door"); this.matterCollision.addOnCollideStart({ objectA: player, objectB: trapDoor, callback: function(eventData) { // This function will be invoked any time the player and trap door collide const { bodyA, bodyB, gameObjectA, gameObjectB, pair } = eventData; // bodyA & bodyB are the Matter bodies of the player and door respectively // gameObjectA & gameObjectB are the player and door respectively // pair is the raw Matter pair data }, context: this // Context to apply to the callback function });
傳感器app
const player = this.matter.add.sprite(0, 0, "player"); const sensor = this.matter.world.add.rectangle(100, 0, 50, 50, { isStatic: true, isSensor: true }); this.matterCollision.addOnCollideStart({ objectA: player, objectB: sensor, callback: eventData => console.log("Player touched hidden sensor") });
Matter:http://brm.io/matter-js/
插件:https://www.npmjs.com/package/phaser-matter-collision-plugin
更多遊戲教學:www.iFIERO.com -- 爲遊戲開發深感自豪ide