📜 ⬆️ ⬇️

Mouse control as in Agar.io on Phaser.js

Good day, Habr! Most recently, the goal appeared to create an analogue of the game Agar.io. In order not to waste time and not complicate your life, it was decided that it would be easier and faster to make the game using a ready-made game development engine.

My choice fell on phaser.js , since, it seemed to me, there is most of all the teaching material for it and it is fast enough because it is built on the Pixi.js library.

In this part I will tell how to implement mouse control. In the end, we get this result:


So, first of all, we initialize all our variables:
')
var width = window.innerWidth; //   var height = window.innerHeight; //   var game = new Phaser.Game(width, height, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); // canvas  phaser,      . var player; //        . var bg; // ,     

Next comes the preload () function responsible for preloading all the graphic elements of the page, I only have the grid:

 function preload() { game.load.image('background', 'img/grid.png'); } 

After the create () function in which we create our canvas with all the elements on it:

 function create() { game.time.advancedTiming = true; game.time.desiredFps = 60; // fps game.time.slowMotion = 2.0; //      ,   0,   2,         bg = game.add.tileSprite(0, 0, 8000, 8000, 'background'); //   game.world.setBounds(0, 0, 8000, 8000);//   game.stage.backgroundColor = "#000"; //   var bmd = generateCircle('red', 20); //      20px player = game.add.sprite(game.world.centerX, game.world.centerY, bmd); //  game.physics.enable(player, Phaser.Physics.ARCADE); //    ARCADE(   phaser.js) game.camera.follow(player); //     } 

Next in the upload () function, we trigger an event when moving the mouse:

 function update() { game.input.addMoveCallback(function(){ game.physics.arcade.moveToPointer(player, 400); //    ARCADE        }); } 

The render () function is needed for debugging:

 function render() { game.debug.cameraInfo(game.camera, 32, 32); //     } 

Function drawing circle:

 function generateCircle(color, size){ var bitmapSize = size * 2 var bmd = this.game.add.bitmapData(bitmapSize, bitmapSize); bmd.ctx.fillStyle = color; bmd.ctx.beginPath(); bmd.ctx.arc(size, size, size, 0, Math.PI*2, true); bmd.ctx.closePath(); bmd.ctx.fill(); return bmd; } 

That's all, we are ready to manage as in agar.io. Once again the link to the final result.

There are no boundaries of the map and granules while eating which player increases, in the course of development I will try to demonstrate how to implement this, as well as make the game multiplayer for node.js.

Source: https://habr.com/ru/post/329652/


All Articles