Game.js Snipped

Server side logic for Phaser 3 game

by ragesoft

JavaScript

// server side phaser game handling
const phaserConfig = config.Game.phaser;		// passed form jsdom, width: 800, height: 600, physics arcade
const gameStarted = false;

phaserConfig.type = Phaser.HEADLESS;			// extend the config
phaserConfig.scene = {
    preload: preload,
    create: create,
    update: update
  };
phaserConfig.autoFocus = false;
 
function preload() {
    var self = this;
    this.load.image('hero', './assets/hero.png');
}
 
function create() {
    var self = this;
    this.heros = this.physics.add.group();					// the main group of my heros to collid with world / each other
    this.physics.add.collider(this.heros, this.heros);
}
 
// send game state infos to all connected clients
function update( time, delta) {
    var self = this;
    var heroData = [];		// gather up all infos of current players

    // moving heros, check if they send some key inputs
    self.heros.getChildren().forEach( hero => {
        // rotate left / right
        if( hero.keys.left ){
            console.log("Setting angle velocity");
            hero.setAngularVelocity( -300 );
        }else if( hero.keys.right ){
            console.log("Setting angle velocity");
            hero.setAngularVelocity( 300 );
        }else{
            hero.setAngularVelocity( 0 );
        }
        // move forward / backward
        if( hero.keys.up ){
            console.log("Setting velocity" + hero.rotation + " X: " + hero.x + " Y: " + hero.y);
            self.physics.velocityFromRotation( hero.rotation, 200, hero.body.velocity);
        }else if( hero.keys.down ){
            console.log("Setting velocity");
            self.physics.velocityFromRotation( hero.rotation, -200, hero.body.velocity);
        }else{
            hero.setAcceleration(0);
            hero.setVelocity( 0 );
        }

		// this is my fix, because setCollideWorldBounds seems not to work...
		// without this fix, player-position is out of borders fast (e.g. X: -8000, Y: -1000);
        if( hero.body.position.x...