This is the sixth day of my participation in Gwen Challenge

preface

I developed web games using AS3 as metal slug for a long time. Now after the decline of Flash, a new generation of H5 game engines have emerged, including Coco2d. js, Unity-2D, Laya, and Egret2D and Egret3D. Egret is recommended if you’re comfortable with TS, or if you’re a fan of native JS (and you already support TS, so why not try Egret?). Today I’m going to take you through Phaser, a lightweight, efficient and free H5 engine.

review

Phaser is an open source, free framework for H5 2D game development. It supports JS and TS, is based on the Pixi.js engine, and has built-in physical properties for game objects. It supports Canvas and WebGL rendering modes, and can be switched between browsers.

Because Phaser is lightweight, easy to use and free to use, there are obvious advantages to developing small games using Phaser. You can reference or install Phaser directly in a Canvas browser to develop games.

The last article talked about the Phaser lifecycle and Phaser resource references, modules for different main functions,

Audio and video import

function preload(){
  game.load.audio("bgmap3"."./assets/audio/bg.ogg");
}
function create(){
  var bgmusic = game.add.audio("bgmap3");
  bgmusic.play();
}
Copy the code

Create an audio object, BGMusic, to play, pause, and adjust the volume. Note: Because of cross-domain, loading of audio files requires setting up a local server.

// Common audio apis include play, pause, resume, stop, segmenting, fade in and out
  this.preload = function(){
    game.load.audio('music'.'asset/sound/1.mp3');
    game.load.image('btn_play'.'asset/sound/btn_play.png');
    game.load.image('btn_pause'.'asset/sound/btn_pause.png'); 
    game.load.image('btn_resume'.'asset/sound/btn_resume.png');
    game.load.image('btn_stop'.'asset/sound/btn_stop.png');
  }

  this.create = function(){
    var sound = game.add.audio('music'.0.1);

    var btn_play = game.add.button(260.20.'btn_play'.function(){
      sound.play(); / / play
    });

    var btn_pause = game.add.button(260.145.'btn_pause'.function(){
      sound.pause(); / / pause
    });

    var btn_resume = game.add.button(260.280.'btn_resume'.function(){
      sound.resume(); / / recovery
    });

    var btn_stop = game.add.button(260.415.'btn_stop'.function(){
      sound.stop(); / / stop
    });

    AddMarker (name, start, duration, volume? , loop?) ;
    // Remove the sound.removeMarker(name);
    sound.addMarker('marker1'.5.1);

    / / note
    var btn_play = game.add.button(260.20.'btn_play'.function(){  
      sound.play('marker1'); / / play
    });
    var sound = game.add.audio('music');


    var btn_play = game.add.button(260.20.'btn_play'.function(){      
      sound.fadeIn(3000); / / fade in
    });

    var btn_pause = game.add.button(260.145.'btn_pause'.function(){           
      sound.fadeOut(3000); / / out
    });
Copy the code

Phaser basic events

  • Game. Onblur Lose focus

  • Game. OnFocus gets focus

  • Game. onPause Pause focus

  • Game. OnResume Resume event

  • Game. Scale. OnFullScreenChange entry, exit full screen

  • Somehow the screen switch game. Scale. OnOrientationChange equipment

  • Game.scale. OnSizeChange Game size changes

  • Game.load. OnFileComplete A single resource is loaded

  • Game.load. OnFileError When the file fails to load

  • Game.load. OnFileStart when the file starts loading

  • Game.load. OnLoadComplete When all resources are loaded

Phaser commonly uses animation

var tween = game.add.tween();

tween.onStart                 // Start animation

tween.onComplete         // The animation is complete

tween.onLoop                // Animation loop

tween.onRepeat            // The animation repeats

var animation = new Phaser.Animation()

animation.onStart          // Start animation

animation.onComplete  // The animation is complete

animation.onLoop         // Animation loop

animation.onUpdate     // When the animation frame changes
Copy the code

Phaser. Input object

It includes mouse events, keyboard events, touch events, and so on.

function create(){
  game.input.onDown.addOnce(function(){
    // Callback event after pressing
  })

  game.input.onUp.addOnce(function(){
    // Press the callback event after leaving
  })

  game.input.onTap.addOnce(function(){
    // The callback event after the tap
  })

  game.input.onHold.addOnce(function(){
    // Callback event after long press
  })

  game.input.addMoveCallback(move,this);
    // Mouse/finger movement monitor

  game.input.deleteMoveCallback(move,this);
    // Remove mouse/finger movement listener
}

function move(){
  document.title = game.rnd.between(0.100)}Copy the code

Phaser. Pointer object

A Pointer object is a Pointer object that can be a mouse, finger, or other input device.

function create(){
  this.pointer = game.input.activePointer;
  // Get a Pointer object
}

function update(){
  document.title = this.pointer.clientX;
  // this.pointer.clientY
  // this.pointer.x / this.pointer.y
  // The x and y coordinates of the pointer event
  if(this.pointer.isDown){
    // The callback after the pointer is pressed
  }
  if(this.pointer.isUp){
    // A callback after the pointer is up}}Copy the code

Phaser. The rid_device_info_keyboard object

function create(){
  // Get the keyboard object
  this.keyboard = game.input.keyboard;

  // Add a key object
  this.keyA = this.keyboard.addKey(Phaser.Keyboard.A);

  // Create a arrow key object
  this.cursor = this.keyboard.createCursorKeys();

  // Listen for all key callbacks, including onDown,onUp...

  this.keyA.onDown.addOnce(function(){
    // The callback function after pressing the custom key object
  })

  this.keyA.onUp.addOnce(function(){
    // The callback function after releasing the custom key
    // If the custom key is still in the pressed state or other states, it will not be executed})}function update(){
  if(this.keyA.isDown){
    // Press the state of the custom key
  }
  if(this.cursor.left.isDown){
    // Press the left key
  }
  if(this.cursor.right.isDown){
    // Press the right key}}Copy the code

For example, in a common business scenario, clicking on a button or clicking on a specific area of the game can be used to pause the game according to the conditions of the game.

function create(){
  game.onPause.add(function(){
    console.log("Game has been suspended.")})}function update(){
  game.paused = true;
}
Copy the code

Game object interaction

Phaser. Events object

A collection of events, attached to the host (the display object in the game), and also partially system events.

function create(){
  game.state.backgroundColor = "#F20";
  this.oBtext = game.add.text(0.0."Test subject");

  // Enable the input event of the object (can receive callback events)
  this.oBtext.inputEnabled = true; 

  // onInputDown, onInputUp, onInputOver, onInputOut Push, release, pass, or leave
  this.oBtext.events.onInputDown.addOnce(testOnDown);
}

function testOnDown(){
  // Click the callback function after "test Object" in the stage
}
Copy the code

Phaser. InputHandler object

Encapsulates host-specific user interaction methods and user input properties.

function create(){
  game.state.background = "#F20";

  this.oBtext1 = game.add.text(0.0."Test subject")
  this.oBtext2 = game.add.text(0.0."Text object")

  this.oBtext2.inputEnabled = true;
  // Turn on the input event of the object (not click on input, but allow event)

  this.inputHandler = this.oBtext2.input;
  // Get the inputHandler object of the text object

  this.inputHandler.disableDrag();
  // Do not drag

  this.inputHandler.enableDrag();
  // Run the drag object

  this.inputHandler.boundsSprite = this.oBtext1;
  // Limit the drag range of oBtext2 to the text size of oBtext1

  this.inputHandler.useHandCursor = true;
  // Whether to use the mouse hand icon

  inputHandler.pointerOver();
  // Check whether the pointer is inside the object

  inputHandler.pointerOut();
  // Determine whether the pointer is outside the object

  inputHandler.pointerX;
  // The x coordinate relative to the object when the pointer is inside the object

  inputHandler.pointerY;
  // The y coordinate relative to the object when the pointer is inside the object

  inputHandler.bringToTop;
  // Whether the object is displayed at the top when clicked or dragged (usually true)
}
Copy the code

The Phaser interaction events are far more extensive, but as someone who has never been a porter of the official API, these are the basic interaction events that I find most common, enough to develop a small pager, and the first things you should learn about Phaser. The specific PAI will be summarized in the form of a table, which is convenient for me and everyone to study together.

Before the game is ready

The general game stage is generally composed of background, elves, stage and other unrelated buildings. As mentioned above, these resources are loaded step by step in the boot function stage or the loading stage. When the resources are loaded, we usually use indicator bars or other forms to inform users of the current state of the game. When all the resources are loaded, you can directly enter the main function of the game, or display a picture or file. User clicks trigger events to enter the game, such as adding events with button or text to enter the main game, for example

function Menu(game) {
  this.preload=function () {
    game.gameData = {
    maps:[
      {name:"map-0".entries: [[7.14.1.1]]},
      {name:"map-1".entries: [[0.8.2.1], [7.0.0.0], [15.12.3.0]]},
      {name:"map-2".entries: [[10.0.2.0], [15.7.1.0], [11.15.4.1]]},
      {name:"map-3".entries: [[0.8.1.2], [9.0.3.1], [13.15.3.2]]}, 
      {name:"map-4".entries: [[0.11.5.0], [5.0.2.2], [7.15.4.2]]},
      {name:"map-5".entries: [[15.4.4.0]]}],currMap:0.currPos: [7.5].currFace:"DOWN".items:[]
    };
  };

  this.create = function() {
    var txt = game.add.text((game.width)/2.200."Tap the screen to start the game.", {fontSize: "16px".fill: "#FFFFFF" });
    txt.anchor.setTo(0.5);  
    game.input.onDown.add(function(){game.state.start("main"); },this);
  };
}
Copy the code

conclusion

As the next installment begins, we’ll start documenting the actual game, and eventually achieve a Phaser version of fingertip Adventure.