Jump to content

Phaser multiplayer map realtime


P4nch0
 Share

Recommended Posts

Hi everyone,

I am creating project, where player have his backyard map and some other maps where he can work ( farmer, fisher etc). Now data from database are loading to phaser using php and ajax. Maps are created in tiled editor and loaded to phaser by standard function, preload, create, update :)

Now i want to create map where players will be able to cooperate in real time. So, players will be have maps where will be only one, and them go to the map where will be cooperate with other players (something like market plaece :))

It will be websocet needed? Maybe i must to recreate everything to websocket because on php can be lagg? Maybe data to maps singleplayer can be loaded by php and ajax but to multiplayer must socket?

Please tell me Your opinion :)

 

Here i found tutoriale, where in phaser is created multiplayer maps, what do you think about it?

I will be gratefull for every feedback :)


 
Link to comment
Share on other sites

yeah, I'd use nodejs websockets if I were you. Well yeah I think it would be more simple if you used all javascript(nodejs for backend), but it is possible to do it like php sends some stuff and then the socket will be with nodejs. As I understand you are using phaser so you can just create socket connection in the game state, for how to do it just watch this :

 

Link to comment
Share on other sites

23 minutes ago, tips4design said:

Depends what you mean by "realtime". Usually "farming" games are not realtime, they just check for changes once in a while, not at 60FPS. If you need a 60FPS multiplayer game then Node.js will be the best thing to go with for HTML5 games,

well actually yes, specially if the game is like Runescape or LoL styled that you click where you want to move, so in this case just stick with php and it will work totally fine

Link to comment
Share on other sites

Very thanks for opinion and materials, i will analyze them :)

I would like to something like that:

Player is coming to this map and see other players, can collide with them and them iteract, make shop to sell and buy , send pm and other iteract :)

I think it musnt be 60 fps. You are right about farming game are not multiplayer, but in my game will be a lot of proffesion so i want to make some part of village where everyone can interact with other :)

Ok to the socket i can read, but how to start think to do it with php? You dont think when in the game will be 500 players can be laggs when will be a lot of request to database?

Link to comment
Share on other sites

Ehh i am trying to add multiplayer from this course: http://ezelia.com/2014/tutorial-creating-basic-multiplayer-game-phaser-eureca-io

This is the same base what i have, i tried to add code from this course to my game, but i doesnt work.. Maybe someone can help me implement serwer and creating players to my game? Please help i really nee to me..

So in this tutorial we can se file serwer.js, but what i saw it is runnig on local host, so my firts qestion is how to run this connection on page which is on online serwer?

Next qestion is how to create players in this multiplayer map? How to show player other players?

What to make about it will be possible in chosen map i think a know, because it can be :

if (this.map == xxx)

But please help me and tell ho to start it.. below my main function in game (i cut it  beacause some elements are dosent need now)

Preload:

var TopDownGame = TopDownGame || {};

//loading the game assets
TopDownGame.Preload = function(){};

TopDownGame.Preload.prototype = {
  preload: function() {
    //show loading screen
    this.preloadBar = this.add.sprite(this.game.world.centerX, this.game.world.centerY, 'preloadbar');
    this.preloadBar.anchor.setTo(0.5);
    
    this.load.setPreloadSprite(this.preloadBar);
    
    //load game assets
    this.load.tilemap('podworko', 'assets/tilemaps/podworko.json', null, Phaser.Tilemap.TILED_JSON); 

    this.load.spritesheet('player', 'assets/images/player.png',64,64);



    
  },
  create: function() {
    this.state.start('Game');
  }
  
   
};// JavaScript Document

In file game.js i have function create, some functions to create objects and map from tilemap.josn file created in tilededitor, and update function:

var TopDownGame = TopDownGame || {};
start();
startdanemapa();
//title screen 

TopDownGame.Game = function(){};
 
TopDownGame.Game.prototype = {

  create: function() {
     
     
   
    this.map = this.game.add.tilemap(TopDownGame.level);
    //the first parameter is the tileset name as specified in Tiled, the second is the key to the asset
    this.map.addTilesetImage('tiles1', 'gameTiles1');
    this.map.addTilesetImage('tiles', 'gameTiles');
    this.map.addTilesetImage('dungeon', 'gamedungeon');
    this.map.addTilesetImage('srodekdom', 'gamesrodekdom');
    this.map.addTilesetImage('towntiles', 'gametowntiles');
    this.map.addTilesetImage('terrain_atlas', 'gameterrain_atlas');
    this.map.addTilesetImage('zew5', 'gamezewnetrzne');
    this.map.addTilesetImage('all3', 'gameall');
    //create layer
    this.backgroundlayer = this.map.createLayer('backgroundLayer');
    this.blockedLayer = this.map.createLayer('blockedLayer');
    this.backgroundLayer2 = this.map.createLayer('backgroundLayer2'); 
    this.blockedLayer1 = this.map.createLayer('blockedLayer1');
    this.secondLayer = this.map.createLayer('secondLayer');
    this.thirdLayer = this.map.createLayer('thirdLayer');
    this.funkcje = this.map.createLayer('funkcje');
    //collision on blockedLayer
     this.map.setCollisionBetween(1, 10000, true, 'blockedLayer');
     this.map.setCollisionBetween(1, 10000, true, 'blockedLayer1');
     this.map.setCollisionBetween(1, 10000, true, 'funkcje');


    this.animal = this.game.add.physicsGroup(Phaser.Physics.ARCADE);

         //this.game.physics.arcade.enable(this.animal);  
    //this.animal.enableBody = true;  
     //this.funkcje.debug = true; 
     
    //resizes the game world to match the layer dimensions
    this.backgroundlayer.resizeWorld();

    this.createItems();
    this.createDoors();
        
    this.createmapa();  
//create player
        
   // var result = this.findObjectsByType('playerStart', this.map, 'objectsLayer')
   
    //this.point = new Phaser.Point(playerx,playery);
      //this.player = this.game.add.sprite(result[0].x, result[0].y, 'player', 5);
     //this.player = this.game.add.sprite(this.point.x, this.point.y, 'player', 5);
  
  
     

     

   if (zmiennastart != 0){

    this.player = this.game.add.sprite(parseInt(playerx), parseInt(playery), 'player', 5);

    
    } 
    
    else
    {this.player = this.game.add.sprite(parseInt(playerx), parseInt(playery), 'player', 5);}                                                                    
     
     
    

    this.game.physics.arcade.enable(this.player );

    this.player.anchor.set(.5);
    this.player.scale.x=70/100;
    this.player.scale.y=65/100;
    this.player.body.setSize(25, 60, 0, 5);
    this.player.body.collideWorldBounds=true;
     //this.game.debug.body(this.player); 

    
    //the camera will follow the player in the world
    this.game.camera.follow(this.player);
      

    
     this.physics.startSystem(Phaser.Physics.Arcade);    


	//this.input.onDown.add(this.moveSprite, this);
    this.goToX = this.player.x + this.camera.x;
    this.goToY = this.player.y + this.camera.y;
    
    //do ruchu na klick usunac do ruchu na klick i trzymanie
    //this.game.input.onDown.add(this.movesprite, this);
    //move player with cursor keys

            this.cursors = this.game.input.keyboard.createCursorKeys();

            this.wasd = {
                up: this.game.input.keyboard.addKey(Phaser.Keyboard.W),
                down: this.game.input.keyboard.addKey(Phaser.Keyboard.S),
                left: this.game.input.keyboard.addKey(Phaser.Keyboard.A),
                right: this.game.input.keyboard.addKey(Phaser.Keyboard.D),
            };
          
                                                            
                                       
    this.player.animations.add('left', [  117, 118, 119, 120, 121, 122, 123],8, true);
    this.player.animations.add('right', [ 143, 144, 145, 146, 147, 148, 149], 8, true);
    this.player.animations.add('down', [132, 133, 134, 135, 136, 137, 138], 8,true);
    this.player.animations.add('up', [105, 106, 107, 108, 109, 110, 111], 8,true);
    
    cutleft = this.player.animations.add('cutleft', [  169, 170, 171, 172, 173], 8);
    cutright = this.player.animations.add('cutright', [  195, 196, 197, 198,199],8);
    cutdown = this.player.animations.add('cutdown', [ 182, 183, 184, 185, 186],8);
    cutup = this.player.animations.add('cutup', [  156, 157, 158, 159,160,],8);
    
    //this.game.input.onDown.add(this.moveSprite, this);


     cutleft.onComplete.add(this.animationStopped, this);
     cutright.onComplete.add(this.animationStopped, this);
     cutdown.onComplete.add(this.animationStopped, this);
     cutup.onComplete.add(this.animationStopped, this);
     this.game.input.onDown.add(this.createeq, this); 
     
     




     
      

   },

createItems: function() {
    //create items  
    this.items = this.game.add.group();
    this.items.enableBody = true;

    var result = this.findObjectsByType('item', this.map, 'objectsLayer');
    result.forEach(function(element){
      this.createFromTiledObject(element, this.items);
    }, this); 
   
    this.items.setAll('body.immovable', true);
    this.items.setAll('body.moves', false);

    
  },
  
  createDoors: function() {
    //create doors
    this.doors = this.game.add.group();
    this.doors.enableBody = true;
    result = this.findObjectsByType('door', this.map, 'objectsLayer');

    result.forEach(function(element){
      this.createFromTiledObject(element, this.doors);
    }, this);
  },


  //find objects in a Tiled layer that containt a property called "type" equal to a certain value
  findObjectsByType: function(type, map, layer) {
    var result = new Array();
    map.objects[layer].forEach(function(element){
      if(element.properties.type === type) {
        //Phaser uses top left, Tiled bottom left so we have to adjust
        //also keep in mind that the cup images are a bit smaller than the tile which is 16x16
        //so they might not be placed in the exact position as in Tiled
        element.y -= map.tileHeight;
        result.push(element);
      }      
    });
    return result;
  },
  //create a sprite from an object
  createFromTiledObject: function(element, group) {
    var sprite = group.create(element.x, element.y, element.properties.sprite);

      //copy all properties to the sprite
      Object.keys(element.properties).forEach(function(key){
        sprite[key] = element.properties[key];
      });    
  },

update: function() {
     

  
    //collision
    this.game.physics.arcade.collide(this.player, this.blockedLayer);
    this.game.physics.arcade.collide(this.player, this.blockedLayer1);
    this.game.physics.arcade.collide(this.player, this.animal, this.stopanimplayer, null, this); 
    this.game.physics.arcade.collide(this.animal, this.animal, this.stopanimzwierz, null, this);    
    this.game.physics.arcade.collide(this.animal, this.blockedLayer, this.stopblocked, null, this);
    this.game.physics.arcade.collide(this.animal, this.funkcje, this.stopblocked, null, this);
    this.game.physics.arcade.overlap(this.animal, this.doors, this.stopblocked, null, this);
    this.game.physics.arcade.collide(this.player, this.funkcje, this.wyborfunkcji, null, this);  
    this.game.physics.arcade.collide(this.player, this.additems);
    this.game.physics.arcade.collide(this.player, this.items, this.funkcjaitem, null, this);
    this.game.physics.arcade.overlap(this.player, this.doors, this.enterDoor, null, this);
    this.game.physics.arcade.overlap(this.player, this.Homedoors, this.enterHomeDoor, null, this);
    this.game.physics.arcade.collide(this.player, this.eqgroup, this.wyborfunkcji, null, this);   
    this.game.physics.arcade.collide(this.player, this.stol, this.stolf, null, this);  
    



//below player movement, animation, collision etc

}

 

So, no meybe somene can help me to start implement multiplayer and serwer to this game? I will be veeery verry gratefull! I hope!

 

Link to comment
Share on other sites

well so that you would get the basic idea of how it works, when a new player connects, or joins the game room, the same map or whatever, then that player sends a message to the (the code does it not the player himself ofc) server, server then sends a message to other players online, now all players spawn a new player(a sprite to show where other player is) in their client, when a player moves then he sends a message again to the server, server sends a message to all other players and so on...

Link to comment
Share on other sites

Thanks for interest :)

Ok, so it sounds grate, but now how to implement this serwer to the game and how i phaser read informationf sending from the serwer?

That what i see in example in file serwer js is done any operation of add player?

This line?

console.log('SPAWN');
var tnk = new Tank(i, game, tank);
tanksList[i] = tnk;

 

if i think good, when player woll come to the map i must sent to the serwer information about create it, but which line it is?

Link to comment
Share on other sites

Hi everyone!

I read and read again this tutorial, and i found interest information for me.

But first qestion is obout library eureca.io, in this tutorial author add library to the file that line:

<script src="/eureca.js"></script>

 

 eureca is a big library, but i dont see file eureca.js

here link to library:

https://github.com/Ezelia/eureca.io

 

So if anyone can, pelase help and tell how to add this library on page.

 

Next, by that command:

node server.js
npm install engine.io
npm install eureca.io

 

is creating serwer, but what i think it is local serwer. What i roead by code below it is attach it to the HTTP , but i cant uderstand how i can do it on my page.

//get EurecaServer class
var EurecaServer = require('eureca.io').EurecaServer;
 
//create an instance of EurecaServer
var eurecaServer = new EurecaServer();
 
//attach eureca.io to our http server
eurecaServer.attach(server);

 

Then, when serwer is ready is starting create() function:

 

 
var ready = false;
var eurecaServer;
//this function will handle client communication with the server
var eurecaClientSetup = function() {
	//create an instance of eureca.io client
	var eurecaClient = new Eureca.Client();
	
	eurecaClient.ready(function (proxy) {		
		eurecaServer = proxy;
		
		
		//we temporary put create function here so we make sure to launch the game once the client is ready
		create();
		ready = true;
	});	
}

To do it i should off automaticall start create function like that:

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: eurecaClientSetup, update: update, render: render });

 

But i done my game by course too and in my game it is looking like that:

Firts i start by main.js file:

var TopDownGame = TopDownGame || {};

TopDownGame.game = new Phaser.Game(700, 600, Phaser.AUTO, 'TRESC');

TopDownGame.game.state.add('Boot', TopDownGame.Boot);
TopDownGame.game.state.add('Preload', TopDownGame.Preload);
TopDownGame.game.state.add('Game', TopDownGame.Game);


TopDownGame.game.state.start('Boot');// JavaScript Document

netx is starting Boot.js file:

 

var TopDownGame = TopDownGame || {};

TopDownGame.Boot = function(){};

//setting game configuration and loading the assets for the loading screen
TopDownGame.Boot.prototype = {
  preload: function() {
    //assets we'll use in the loading screen
    this.load.image('preloadbar', 'assets/images/preloader-bar.png');
  },
  create: function() {
    //loading screen will have a white background
    this.game.stage.backgroundColor = '#fff';

    //scaling options
    this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
    
    //have the game centered horizontally
    this.scale.pageAlignHorizontally = true;
    this.scale.pageAlignVertically = true;

    //screen size will be set automatically
    this.scale.setScreenSize(true);

    //physics system
    this.game.physics.startSystem(Phaser.Physics.ARCADE);
    
    this.state.start('Preload');
  }
};// JavaScript Document

 

And them prealod.js file, and gaim.js file which you can see in my before post. So now i dont know which create() function i need to start after ready serwer.

So that is to start i think.. If anyone have some time, pelase help motivated person to study programing :)

 

 

Link to comment
Share on other sites

Here i found a nice topic about multiplayer in phaser:

So, i think better solution will be when i use connection with database. But what i should to do it?

I need to have any table in data base where will be x,y and id player?

Them i need to all time sendinq request using ajax to the data base and if it different them move the object to the actual point?

Link to comment
Share on other sites

What you do is you run Phaser in headless mode on your server. Then move sprites on the server and update your client. I believe ajax would be much slower then websockets but depending on how quick you want everything to update it might not be a big deal. The database method seems like it would be to much work and too many calls aka slow, but depending on how simple everything is that could work too.

Link to comment
Share on other sites

Yeah, PHP and AJAX aren't a good choice for a lot of online game types. The problem is that you can't easily send messages from the server to players without them making a request. It is possible to do what is called "long polling" where you have every client send requests that are then held by the server until data needs to sent to them but this is a less than optimal choice because it is very taxing on the server and connections will often be timing out and require they be resent, so with the overhead of HTTP, this is not a great solution.

Node and WebSockets are a better solution. I remember looking before at Eureca and was turned off from it for some reason but honestly I can't remember what it was so that is probably neither here nor there. If you are going node, you can always just use the very popular Socket.io. 

But to answer your question, I assume that the "eureca.js" file is probably the EurecaClient.js file in the /lib folder. The client script is the one on the client side that knows how to connect to the server. 

EDIT: Oh, it is worth noting that in Socket.io, there is a script tag on the client to a Javascript file that isn't found in the source code of Socket.io. That is because that file is generated by Socket.io once the server is running. That may also be the case with Eureca, where the server may specially package a client script for the browser. See if that may be the case for Eureca if the EurecaClient.js script isn't the right one. 

Link to comment
Share on other sites

Thanks for Your answer friends.

I'll try to make yesterday some examples with socket.io, but this is very hard for me to understand. I dont have idea how to start it..

Maybe someone can tell me step by step with what file i need to start.

If i think good i should start connect in main page where i have a game screen. Them i should transfer data to the game.js where i have mai code of game (create and update function), and what next?

What i should do in phaser? I should check to see if anything has changed and them do it with sprite in phaser?

First question is what i need, what i wrote i need node js to instal serwer, but i wrote something obout npm, bu i dont found anything.

If someone can write me step by step what i need download, what i need to instal in node js, and them help to download data from mysql data base( player name, x, y position) and how to export it to the Phaser file to the update funcion.

I will be very gratefull.

Link to comment
Share on other sites

Have you checked out server-sent events? https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

You'll have to do some work correlating requests from the browser to the proper open channel, but it's another way to send events from the server to the browser. It has lots of browser support, too.

Link to comment
Share on other sites

Ok, ii'm trying and trying to do some examples.

 

I have a qestion because i dont have a nice tutorial talking step by step..

Command to instal node, npm and mysql and other commens i must use in cmd console or in node console?

I found some commend which give me wrong in cmd and node console..

 

For example, in this tutorial author is using cmd or node console?

http://javascript-html5-tutorial.com/node-js-introduction.html

 

He linked node.js and npm to download, but i new wersion node npm is in it yes?

I know about this is something other than phaser but after i do examples i will try to add it to phaser and write You effects :)

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...