Phaser specific versions in this article

Phaser2:2.8.1 Phaser3:3.17.0Copy the code

Implementation effect 2 implementation details 3 Project summary 4 Reference documents

One, achieve the effect



Source address (phaser2 & phaser3) : https://github.com/winniecjy/phaser-dadishu/

Experience the address: https://winniecjy.github.io/phaser-dadishu/ver-phaser2/dist/

Second, implementation details

This demo was actually made when we were learning phaser2, and is now used for Phaser3, just to get a sense of how much the new API changes are. In the logical order of the game’s implementation, here’s a rundown of the Phaser3 APIS used, as well as a brief comparison with the Phaser2 API.

Step 1: Initialize the gamenew Phaser.Game

Initialize the canvas parameters, including the width and height of the canvas, the render method, and insert them into the DOM structure. Phaser3 replaces States with scenes in Phaser2 to avoid confusion with the concept of state machines. A scene in a game is an independent scene with its own resources, including camera system, display list, update steps, event handling, physics system, and so on. The game can only execute one scene at a time, and a scene is maintained by multiple hook functions, including init, preload, create, update, etc.

/ / phaser 3: https://photonstorm.github.io/phaser3-docs/Phaser.Types.Core.html#.GameConfig
conf = {
  width: 750.height: 750/window.innerWidth*window.innerHeight,
  type: Phaser.AUTO, // Render method
  parent: 'container'.// Will contain the DOM element of the game canvas
  backgroundColor: '#f9c04c'.scale: {
      mode: Phaser.Scale.FIT // 缩放模式,此处按比例调整画布大小,相当于contain
  },
  scene: { // Initialize the scene at the beginning of the game
    init: function(){ 
        // Execute first when the scene starts, which can be used to initialize variables or redirect to other scenarios
    },
    preload: function(){ 
        // The second function, which preloads game resources, does not create objects here
    },
    create: function(){
        // When preload completes, the preload resource is loaded, and the object can be created here
    },
    update: function(){ 
        // Canvas update, executed every frame of the game
    },
    / /... Other functions
  }
}
game = new Phaser.Game(conf);

/ / phaser 2: http://phaser.io/docs/2.6.2/Phaser.Game.html
game = new Phaser.Game(750.750/window.innerWidth*window.innerHeight, Phaser.AUTO, 'container', 
  { // Initialize the scene at the beginning of the game
    init: function(){ 
        // Execute first when the scene starts, which can be used to initialize variables or redirect to other scenarios
    },
    preload: function(){ 
        // The second function, which preloads game resources, does not create objects here
    },
    create: function(){
        // When preload completes, the preload resource is loaded, and the object can be created here
    },
    update: function(){ 
        // Canvas update, executed every frame of the game
    },
    / /... Other functions
  })

Copy the code

Step 2: Preload resources

This part of the API is basically the same as Phaser3, but phaser3 has changed the Game object structure. Phaser2 has a tree structure, and all objects in the Game come from the root object phaser. Game. Objects also have children of their own. Phaser3 unpacks these objects. The Game object Phaser.Game contains no other object group, and the object group does not have any positions or properties.

// phaser3: https://photonstorm.github.io/phaser3-docs/Phaser.Loader.LoaderPlugin.html preload: function () { console.log("start loading ..." ); this.numbersJson = require('.. /json/numbers.json'); // loader mounts this. Load. Image ('bg', './img/holes-bg.png'); this.load.image('hamster', './img/hamster.png'); this.load.image('hammer', './img/hammer.png'); this.load.image('lightning', './img/lightning.png'); this.load.atlas('sprite_numbers', './img/numbers.png', this.numbersJson); this.load.on('complete', loadProgress); Function loadProgress(loader, finishedNum) {console.log(' ${finishedNum} ') `); $(" cjy_panel. Start_btn "). Click (function () {/ / remove the start interface $(". Cjy_panel "). Hide (); customGame.scene.start('play'); })}} / / phaser2: http://phaser.io/docs/2.6.2/Phaser.Loader.html preload: function () {the console. The log (" start loading..." ); this.numbersJson = require('.. /json/numbers.json'); Console. log(window.customgame) // These properties have been removed in Phaser3, Need through the initialization configuration window. CustomGame. Scale. The scaleMode = Phaser. ScaleManager. SHOW_ALL; window.customGame.stage.backgroundColor = '#f9c04c'; / / loader is mounted in the Phaser. Under the game window. CustomGame. Load. The image (' bg ', '.. / img/holes - bg. PNG '); window.customGame.load.image('hamster', './img/hamster.png'); window.customGame.load.image('hammer', './img/hammer.png'); window.customGame.load.image('lightning', './img/lightning.png'); window.customGame.load.atlasJSONHash('sprite_numbers', './img/numbers.png', '', this.numbersJson); window.customGame.load.onLoadComplete.add(loadProgress, this); Function loadProgress() {console.log(' Resources loaded, ready to start! ') $(".cjy_panel.start_btn ").click(function () {console.log(" Start the game! ); $(".cjy_panel").hide(); customGame.state.start('play'); }}})Copy the code

Step 3: Create the object

Creating an object is usually done in the CREATE function, and this part of the API is basically the same. The difference is similar to load, because the overall data structure has been modified.

// phaser3: https://photonstorm.github.io/phaser3-docs/Phaser.GameObjects.GameObjectCreator.html / / object to create this. Hammer = This. The add. Sprite (hammerx, hammery, 'hammer'). SetOrigin (0, 0.8); // phaser2: http://phaser.io/docs/2.6.2/Phaser.GameObjectFactory.html this. Hammer = customGame. Add. Sprite (hammerx hammery, 'hammer'); This. Hammer. Anchor. SetTo (0, 0.8);Copy the code

Step 4: Animation

Phaser2 and Phaser3 both provide built-in Tween animations for developers to use. Compared with Phaser2, the tween animation configuration in Phaser3 is more flexible and rich. See the official documentation for a complete list of configuration items.

// phaser3: https://photonstorm.github.io/phaser3-docs/Phaser.Tweens.TweenManager.html this.tweens.add({ targets: [this.hammer], angle: 45, duration: 50, callbackScope: this, ease: 'Linear' }) // phaser2: http://phaser.io/docs/2.6.2/Phaser.Tween.html var rotateTween = customGame. Add. Tween (enclosing hammer); rotateTween.to({ angle: 45 }, 50, Phaser.Easing.Cubic.In, true);Copy the code

Step 5: Interactive behavior

Phasers have no DOM concept, and all interactions rely on the PHASer API, which manages all Input events through phaser. Input. When an interaction occurs, the interacting phaser. Game object dispatches an event down, and Phaser3 can listen for this event in the Scene /gameObject. Different locations listen for events with different scopes and priorities. Higher priority event handlers can stop Propagation to lower priority events.

// phaser3: https://photonstorm.github.io/phaser3-docs/Phaser.Input.Events.html this.input.on('pointerdown', onTap, this); function onTap(pointer,currentlyOver) { ... } / / phaser2: http://phaser.io/docs/2.6.2/Phaser.Input.html customGame. Input. OnTap. Add (onTap, this); function onTap(pointer, doubleTap) { ... }Copy the code

Step 6: Timer

// phaser3: https://photonstorm.github.io/phaser3-docs/Phaser.Time.TimerEvent.html this.time.addEvent({ loop: true, delay: 1000, callback: timerFn, callbackScope: this }) // phaser2: http://phaser.io/docs/2.6.2/Phaser.Timer.html#loop customGame. Time. Events. Loop (Phaser. Timer. SECOND, the enclosing timerFn, this);  / / use the clock object to repeat. Produce pipe customGame time. Events. The start ();Copy the code

Iii. Project Summary

Some details that could be improved:

  • [Front end] Resource preloading should be in the same scene as the game process. The logic was not clear before, which separated the two steps
  • 【 Interaction 】 Crazy click page will appear a lot of small hammers, a short time multiple click should only respond once
  • [Interaction] Improved feedback when hitting gophers, such as gophers have stun effect/sound prompt /+1 effect, etc
  • 【 Gameplay 】 Gophers appear faster and faster
  • [Gameplay] The protagonist is diverse, in addition to the gopher can also have bombs/gopher holding gifts/other props, different scores

Phaser2 is fast to get started with, has a simple API, and is rich in official documentation examples, so it’s worth exploring and trying out the physics engine later. Phaser3 is a release under development that has a lot of changes compared to the Phaser2 API and is not fully documented. It is basically a source code guessing API. In testing the water, you can feel phaser3 rethinking the API design, such as using objects instead of primitive data types as function parameters, for better readability and flexibility. In addition, Phaser3 has enhanced camera functionality, including support for the matter.js physics engine and 2D skeleton animation. Or check out the new Phaser3 game engine feature list (from Bump Lab). About self-learning: I find the phaser API’s most intuitive way to learn is to print it on the console, especially for beginners who don’t have a clear understanding of the structure and can easily get confused by looking at the documentation. For details, see the official examples. After the rainbow fart is over, I have to say that for actual project use, it is recommended to use the stable version of Phaser2.

Vi. Reference documents

  1. Phaser’s website: http://phaser.io/
  2. Phaser2 API documentation: http://phaser.io/docs/2.6.2/index
  3. Phaser3 API documentation: https://photonstorm.github.io/phaser3-docs/
  4. Phaser3 Official example: https://labs.phaser.io/
  5. New Phaser3 game engine features list: https://aotu.io/notes/2018/12/23/phaser3/

AD time

Feizhu is bytedance’s office suite product, which deeply integrates functions such as instant communication, online collaboration, audio and video conferencing, calendar, cloud disk and workbench to provide users with one-stop collaboration experience. At present, feishu service customers have covered science and technology, Internet, information technology, manufacturing, construction and real estate, enterprise services, education, media and other fields. Welcome to the bytedance flying book team, there are a large number of front-end and back-end HC ~ scan the TWO-DIMENSIONAL code or click the link to send, look for the flying book team 👍 ~

Internal push code: HZNVPHS, delivery link:job.toutiao.com/s/JaeUCoc

[Recruitment] Delivery link:job.toutiao.com/s/JaevUNo