var collider= this.physics.add.overlap(player, pipe, perder, false, this); - phaser-framework

Im making this game and I got some problems with an overlap function.
So, the main problem is, when the player touch 2 pipes at same time, the player loses 2 lives instead of 1. This occurs because player touches 2 pixels at same time, 1 from one pipe and 1 from another. So I create this collider flag "collider" to just call one time the function "perder" and not 2 like previously.
...
addOnePipe: function(x, y) {
pipe = this.physics.add.image(x, y, 'br').setScale(1.1);
pipe.setVelocityX(-150);
this.pipes.addMultiple(pipe);
pipe.checkWorldBounds = true;
pipe.outOfBoundsKill = true;
***var collider = this.physics.add.overlap(player, pipe, perder, false, this);***
},
addRowOfPipes: function() {
var hole = Phaser.Math.Between(1, 6);
//var hole=6;
enter code here
for (var i = 0; i < 8; i++)
if (i != hole && i != hole + 1){
this.addOnePipe(760, i *54 + 40);
}
},
});
***function perder (player,pipe) {
vida--;
if (vida==0){
this.scene.start('gameover');
}
else(this.scene.start('game2'));
collider.active = false;
}***
The full game is here:
var Preloader = new Phaser.Class({
Extends: Phaser.Scene,
initialize:
function Preloader ()
{
Phaser.Scene.call(this, { key: 'preloader' });
},
preload: function ()
{
this.load.image('imgfinal', 'https://cdn.shopify.com/s/files/1/0769/4313/products/GAMEOVER_copy_1024x1024.jpg?v=1508717540');
this.load.image('br', 'assets/sprites/crate32.png');
this.load.image('ground2', 'http://images6.fanpop.com/image/photos/40700000/Backround-geometry-dash-40776456-250-250.jpg');
this.load.image('sky', 'https://st2.depositphotos.com/7267546/10689/v/950/depositphotos_106891270-stock-illustration-cartoon-nature-landscape-for-game.jpg');
this.load.image('final2', 'http://3.bp.blogspot.com/--aDP7X-70Yo/T0epwcsA0EI/AAAAAAAAAjU/D6b1H0gs8_4/s1600/fixe+5+estrelas.jpg');
this.load.image('final', 'https://images-na.ssl-images-amazon.com/images/I/81MPs6C9M8L._SY355_.png');
this.load.image('ground', 'https://lh3.googleusercontent.com/-8_3XLw9ontM/VsmYVcGUStI/AAAAAAAAAgE/ZGFffMQDNFw/w318-h318-n-rw/bg_03.png');
this.load.image('bomb', 'src/games/firstgame/assets/bomb.png');
this.load.image('sky2', 'https://st2.depositphotos.com/5479200/11693/v/950/depositphotos_116931742-stock-illustration-game-background-2d-application-vector.jpg');
this.load.image('triangle', 'assets/sprites/triangle.png');
this.load.image('branco', 'https://madeirasgasometro.vteximg.com.br/arquivos/ids/170727-490-490/pp40-branco-neve-square.jpg?v=636801256712100000');
this.load.image('back','https://http2.mlstatic.com/piso-de-granito-verde-ubatuba-D_NQ_NP_798225-MLB25401365082_022017-F.jpg');
this.load.image('play', 'https://http2.mlstatic.com/revestimento-adesivo-decofix-marmore-cinza-2-metros-D_NQ_NP_421311-MLB20503488532_112015-F.jpg');
this.load.spritesheet('dude', 'src/games/firstgame/assets/dude.png', { frameWidth: 32, frameHeight: 48 });
this.load.image('tubo', 'assets/sprites/block.png');
this.load.audio('drums', ['assets/audio/tech/drums.ogg', 'assets/audio/tech/drums.mp3']);
this.load.audio('synth2', ['assets/audio/tech/synth2.ogg', 'assets/audio/tech/synth2.mp3']);
this.load.audio('boden', ['assets/audio/bodenstaendig_2000_in_rock_4bit.mp3', 'assets/audio/bodenstaendig_2000_in_rock_4bit.ogg']);
this.load.image('reverse','http://www.euvosescrevi.com.br/wp-content/uploads/2016/04/earth.jpg');
this.load.image('star', 'src/games/firstgame/assets/star.png');
this.load.setPath('assets/audio/kyobi/');
this.load.audioSprite('kyobi', 'kyobi.json');
},
create: function ()
{
this.scene.start('mainmenu');
}
});
var MainMenu = new Phaser.Class({
Extends: Phaser.Scene,
initialize:
function MainMenu ()
{
Phaser.Scene.call(this, { key: 'mainmenu' });
window.MENU = this;
},
create: function ()
{
vida=3;
var back= this.add.image(400,300,'back');
var play= this.add.image(400,250,'play').setScale(0.2);
var play1;
play1= this.add.image(400,400,'play').setScale(0.2);
this.add.text(240, 70, '"The Runner" ', { font: '50px Arial', fill: '#ffffff' });
this.add.text(337.5, 230, 'PLAY', { font: '50px Courier', fill: '#00000' });
this.add.text(335, 360, 'HOW', { font: '50px Courier', fill: '#00000' });
this.add.text(400, 400, 'TO', { font: '50px Courier', fill: '#00000' });
play1.setInteractive();
play1.once('pointerup', function () {
this.scene.start('rules');
}, this);
play.setInteractive();
play.once('pointerup', function () {
this.scene.start('game2');
}, this);
}
});
var Rules = new Phaser.Class({
Extends: Phaser.Scene,
initialize:
function Rules ()
{
Phaser.Scene.call(this, { key: 'rules' });
window.MENU = this;
},
create: function ()
{
var back= this.add.image(400,300,'back');
var play3= this.add.image(650,500,'play').setScale(0.2);
this.add.text(590, 480, 'BACK', { font: '50px Courier', fill: '#000000' });
this.add.text(20, 40, 'Welcome to "The Runner" ', { font: '50px Times', fill: '#ffffff' });
this.add.text(60, 115, 'Rules: ', { font: '40px Times', fill: '#ffffff' });
this.add.text(65, 180, 'The arenĀ“t any rules for this game. Just give your best to', { font: '30px Times', fill: '#ffffff' });
this.add.text(65, 220, 'complete the maps and DONT USE CHEATS!! ', { font: '30px Times', fill: '#ffffff' });
this.add.text(70, 300, 'Controls: Up Arrow ', { font: '30px Times', fill: '#ffffff' });
this.add.text(190, 350, 'Left Arrow ', { font: '30px Times', fill: '#ffffff' });
this.add.text(190, 400, 'Right Arrow ', { font: '30px Times', fill: '#ffffff' });
this.add.text(328, 304.5, '|', { font: '20px Times', fill: '#ffffff' });
this.add.text(320, 290, '^', { font: '40px Times', fill: '#ffffff' });
this.add.text(332, 353, '<', { font: '30px Times', fill: '#ffffff' });
this.add.text(346, 327, '_', { font: '40px Times', fill: '#ffffff' });
this.add.text(370, 401, '>', { font: '30px Times', fill: '#ffffff' });
this.add.text(350, 375, '_', { font: '40px Times', fill: '#ffffff' });
play3.setInteractive();
play3.once('pointerup', function () {
this.scene.start('mainmenu');
}, this);
}
});
var Game = new Phaser.Class({
Extends: Phaser.Scene,
initialize:
function Game ()
{
Phaser.Scene.call(this, { key: 'game' });
window.GAME = this;
var player;
var platforms;
var cursors;
var tubos;
var timer;
var star;
},
create: function ()
{
drums = this.sound.add('drums');
synth2 = this.sound.add('synth2');
boden = this.sound.add('boden');
var loopMarker = {
name: 'loop',
start: 0,
duration: 7.68,
config: {
loop: true
}
}
drums.addMarker(loopMarker);
drums.play('loop', {
delay: 0
});
synth2.addMarker(loopMarker);
synth2.play('loop', {
delay: 0
});
this.cameras.main.setBounds(0, 0, 5500, 600);
this.physics.world.setBounds(0, 0, 5500, 600);
this.add.image(0, 0, 'sky').setOrigin(0).setScrollFactor(1);
this.add.image(1000, 0, 'sky').setOrigin(0).setScrollFactor(1);
this.add.image(3899.5, 0, 'sky').setOrigin(0).setScrollFactor(1);
this.add.image(2000, 0, 'reverse').setOrigin(0).setScrollFactor(1);
cursors = this.input.keyboard.createCursorKeys();
player = this.physics.add.sprite(100, 300, 'dude').setGravity(0, 300);
this.cameras.main.startFollow(player, true, 0.08, 0.08);
this.cameras.main.setZoom(1);
tubos= this.physics.add.staticGroup();
tubos.create(300, 20, 'tubo').setScale(0.45).refreshBody();
tubos.create(300, 62, 'tubo').setScale(0.45).refreshBody();
tubos.create(300, 177, 'tubo').setScale(0.45).refreshBody();
tubos.create(300, 219, 'tubo').setScale(0.45).refreshBody();
tubos.create(300, 261, 'tubo').setScale(0.45).refreshBody();
tubos.create(300, 303, 'tubo').setScale(0.45).refreshBody();
tubos.create(300, 345, 'tubo').setScale(0.45).refreshBody();
tubos.create(300, 387, 'tubo').setScale(0.45).refreshBody();
tubos.create(300, 429, 'tubo').setScale(0.45).refreshBody();
//------------------------------------------------------------
tubos.create(500, 20, 'tubo').setScale(0.45).refreshBody();
tubos.create(500, 62, 'tubo').setScale(0.45).refreshBody();
tubos.create(500, 104, 'tubo').setScale(0.45).refreshBody();
tubos.create(500, 146, 'tubo').setScale(0.45).refreshBody();
tubos.create(500, 188, 'tubo').setScale(0.45).refreshBody();
tubos.create(500, 230, 'tubo').setScale(0.45).refreshBody();
tubos.create(500, 345, 'tubo').setScale(0.45).refreshBody();
tubos.create(500, 387, 'tubo').setScale(0.45).refreshBody();
tubos.create(500, 429, 'tubo').setScale(0.45).refreshBody();
//------------------------------------------------------------
tubos.create(700, 70, 'tubo').setScale(0.44).refreshBody();
tubos.create(700, 110, 'tubo').setScale(0.44).refreshBody();
tubos.create(700, 150, 'tubo').setScale(0.44).refreshBody();
tubos.create(700, 190, 'tubo').setScale(0.44).refreshBody();
tubos.create(700, 230, 'tubo').setScale(0.44).refreshBody();
tubos.create(700, 270, 'tubo').setScale(0.44).refreshBody();
tubos.create(700, 310, 'tubo').setScale(0.44).refreshBody();
tubos.create(700, 350, 'tubo').setScale(0.44).refreshBody();
tubos.create(700, 390, 'tubo').setScale(0.44).refreshBody();
tubos.create(700, 430, 'tubo').setScale(0.44).refreshBody();
//------------------------------------------------------------
tubos.create(900, 20, 'tubo').setScale(0.44).refreshBody();
tubos.create(900, 60, 'tubo').setScale(0.44).refreshBody();
tubos.create(900, 150, 'tubo').setScale(0.44).refreshBody();
tubos.create(900, 190, 'tubo').setScale(0.44).refreshBody();
tubos.create(900, 230, 'tubo').setScale(0.44).refreshBody();
tubos.create(900, 270, 'tubo').setScale(0.44).refreshBody();
tubos.create(900, 310, 'tubo').setScale(0.44).refreshBody();
tubos.create(900, 350, 'tubo').setScale(0.44).refreshBody();
tubos.create(900, 390, 'tubo').setScale(0.44).refreshBody();
tubos.create(900, 430, 'tubo').setScale(0.44).refreshBody();
//------------------------------------------------------------
tubos.create(1100, 0, 'tubo').setScale(0.44).refreshBody();
tubos.create(1100, 100, 'tubo').setScale(0.44).refreshBody();
tubos.create(1100, 140, 'tubo').setScale(0.44).refreshBody();
tubos.create(1100, 180, 'tubo').setScale(0.44).refreshBody();
tubos.create(1100, 220, 'tubo').setScale(0.44).refreshBody();
tubos.create(1101, 260, 'tubo').setScale(0.44).refreshBody();
tubos.create(1141, 304, 'tubo').setScale(0.50).refreshBody();
tubos.create(1100, 350, 'tubo').setScale(0.44).refreshBody();
tubos.create(1100, 390, 'tubo').setScale(0.44).refreshBody();
tubos.create(1100, 430, 'tubo').setScale(0.44).refreshBody();
//------------------------------------------------------------
tubos.create(1300, 65, 'tubo').setScale(0.43).refreshBody();
tubos.create(1300, 105, 'tubo').setScale(0.43).refreshBody();
tubos.create(1300, 145, 'tubo').setScale(0.43).refreshBody();
tubos.create(1300, 185, 'tubo').setScale(0.43).refreshBody();
tubos.create(1300, 225, 'tubo').setScale(0.43).refreshBody();
tubos.create(1300, 265, 'tubo').setScale(0.43).refreshBody();
tubos.create(1300, 306, 'tubo').setScale(0.43).refreshBody();
tubos.create(1300, 347, 'tubo').setScale(0.43).refreshBody();
tubos.create(1300, 388, 'tubo').setScale(0.43).refreshBody();
tubos.create(1300, 429, 'tubo').setScale(0.43).refreshBody();
//------------------------------------------------------------
tubos.create(1400, 260,'tubo').setScale(0.43).refreshBody();
tubos.create(1450, 95, 'tubo').setScale(0.43).refreshBody();
tubos.create(1570, 95, 'tubo').setScale(0.43).refreshBody();
tubos.create(1690, 95, 'tubo').setScale(0.43).refreshBody();
tubos.create(1810, 95, 'tubo').setScale(0.43).refreshBody();
tubos.create(1930, 95, 'tubo').setScale(0.43).refreshBody();
//---------------------------------------------------
tubos.create(1977, 132, 'tubo').setScale(0.46).refreshBody();
tubos.create(1977, 174, 'tubo').setScale(0.46).refreshBody();
tubos.create(1977, 216, 'tubo').setScale(0.46).refreshBody();
tubos.create(1977, 258, 'tubo').setScale(0.46).refreshBody();
tubos.create(1977, 300, 'tubo').setScale(0.46).refreshBody();
tubos.create(1977, 342, 'tubo').setScale(0.46).refreshBody();
tubos.create(1977, 384, 'tubo').setScale(0.46).refreshBody();
tubos.create(1977, 427, 'tubo').setScale(0.46).refreshBody();
//------------------------------------------------------------
tubos.create(2350, 100, 'tubo').setScale(0.43).refreshBody();
tubos.create(2600, 160, 'tubo').setScale(0.43).refreshBody();
tubos.create(2850, 230, 'tubo').setScale(0.43).refreshBody();
tubos.create(3100, 290, 'tubo').setScale(0.43).refreshBody();
tubos.create(3350, 360, 'tubo').setScale(0.43).refreshBody();
tubos.create(3600, 360, 'tubo').setScale(0.43).refreshBody();
tubos.create(3850, 455, 'tubo').setScale(0.43).refreshBody();
tubos.create(3850, 395, 'tubo').setScale(0.43).refreshBody();
tubos.create(3850, 335, 'tubo').setScale(0.43).refreshBody();
tubos.create(3850, 275, 'tubo').setScale(0.43).refreshBody();
tubos.create(3850, 215, 'tubo').setScale(0.43).refreshBody();
tubos.create(3850, 155, 'tubo').setScale(0.43).refreshBody();
tubos.create(3850, 90, 'tubo').setScale(0.43).refreshBody();
//------------------------------------------------------------
tubos.create(4300, 130, 'tubo').setScale(0.43).refreshBody();
tubos.create(4300, 180, 'tubo').setScale(0.43).refreshBody();
tubos.create(4300, 230, 'tubo').setScale(0.43).refreshBody();
tubos.create(4300, 280, 'tubo').setScale(0.43).refreshBody();
tubos.create(4300, 330, 'tubo').setScale(0.43).refreshBody();
tubos.create(4300, 380, 'tubo').setScale(0.43).refreshBody();
tubos.create(4300, 430, 'tubo').setScale(0.43).refreshBody();
star = this.physics.add.staticGroup();
star.create(4300,90, 'star');
platforms = this.physics.add.staticGroup();
platforms.create(-225, 768, 'ground').setScale(2).refreshBody();
platforms.create(411, 768, 'ground').setScale(2).refreshBody();
platforms.create(1047, 768, 'ground').setScale(2).refreshBody();
platforms.create(1682, 768, 'ground').setScale(2).refreshBody();
platforms.create(4238, 768, 'ground').setScale(2).refreshBody();
platforms.create(4605, 768, 'ground').setScale(2).refreshBody();
//-----------------------------------------------------------------
platforms.create(2047.7,0,'ground').setScale(0.3).refreshBody();
platforms.create(2140, 0, 'ground').setScale(0.3).refreshBody();
platforms.create(2233, 0, 'ground').setScale(0.3).refreshBody();
platforms.create(2326, 0, 'ground').setScale(0.3).refreshBody();
platforms.create(2419, 0, 'ground').setScale(0.3).refreshBody();
platforms.create(2512, 0, 'ground').setScale(0.3).refreshBody();
platforms.create(2605, 0, 'ground').setScale(0.3).refreshBody();
platforms.create(2698, 0, 'ground').setScale(0.3).refreshBody();
platforms.create(2791, 0, 'ground').setScale(0.3).refreshBody();
platforms.create(2884, 0, 'ground').setScale(0.3).refreshBody();
platforms.create(2977, 0, 'ground').setScale(0.3).refreshBody();
platforms.create(3070, 0, 'ground').setScale(0.3).refreshBody();
platforms.create(3163, 0, 'ground').setScale(0.3).refreshBody();
platforms.create(3256, 0, 'ground').setScale(0.3).refreshBody();
platforms.create(3349, 0, 'ground').setScale(0.3).refreshBody();
platforms.create(3442, 0, 'ground').setScale(0.3).refreshBody();
platforms.create(3535, 0, 'ground').setScale(0.3).refreshBody();
platforms.create(3628, 0, 'ground').setScale(0.3).refreshBody();
platforms.create(3721, 0, 'ground').setScale(0.3).refreshBody();
platforms.create(3814, 0, 'ground').setScale(0.3).refreshBody();
platforms.create(3872, 0, 'ground').setScale(0.3).refreshBody();
player.setBounce(0.1);
player.setCollideWorldBounds(true);
this.anims.create({
key: 'left',
frames: this.anims.generateFrameNumbers('dude', { start: 0, end: 3 }),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'turn',
frames: [ { key: 'dude', frame: 4 } ],
frameRate: 20
});
this.anims.create({
key: 'right',
frames: this.anims.generateFrameNumbers('dude', { start: 5, end: 8 }),
frameRate: 10,
repeat: -1
});
this.physics.add.collider(player, platforms);
this.physics.add.collider(player, tubos);
this.physics.add.overlap(player, star, collectStar, null, this);
info = this.add.text(10, 7, '', { font: '48px Arial', fill: '#ff0000' });
info2 = this.add.text(19, 50, '', { font: '48px Arial', fill: '#ff0000' });
timer = this.time.addEvent({ delay: 46000, callback: Gameover,callbackScope: this, });
info.setScrollFactor(0);
info2.setScrollFactor(0);
},
update: function ()
{
if ( player.x >= 2000 && player.x <=3915 ) {
player.angle = -180;
player.setGravity(0, -100);
if (cursors.left.isDown)
{
player.setVelocityX(-90);
player.anims.play('left', true);
}
else if (cursors.right.isDown)
{
player.setVelocityX(90);
player.anims.play('right', true);
}
else
{
player.setVelocityX(0);
player.anims.play('turn');
}
if (cursors.up.isDown && player.body.touching.up)
{
player.setVelocityY(-1500);
}
}
else if (player.x <2000 || player.x>3915){
player.angle=0;
player.setGravity(0, 300);
}
if (cursors.left.isDown)
{
player.setVelocityX(-160);
player.anims.play('left', true);
}
else if (cursors.right.isDown)
{
player.setVelocityX(160);
player.anims.play('right', true);
}
else
{
player.setVelocityX(0);
player.anims.play('turn');
}
if (cursors.up.isDown && player.body.touching.down)
{
player.setVelocityY(-470);
}
info.setText('Time: ' + Math.floor(46000 - timer.getElapsed()));
info2.setText('Lifes: ' + vida);
}
});
var Game2 = new Phaser.Class({
Extends: Phaser.Scene,
initialize:
function Game2 ()
{
Phaser.Scene.call(this, { key: 'game2' });
window.GAME = this;
var timer1;
var platforms;
var player;
var pipe;
var timer2;
pipes=null;
},
create: function ()
{
this.add.image(350, 280, 'sky2').setScale(1.1);
this.pipes = this.add.group();
this.physics.world.enable(this.pipes);
platforms = this.physics.add.staticGroup();
platforms.create(0, 535, 'ground2').setScale(0.6).refreshBody();
platforms.create(150, 535, 'ground2').setScale(0.6).refreshBody();
platforms.create(300, 535, 'ground2').setScale(0.6).refreshBody();
platforms.create(450, 535, 'ground2').setScale(0.6).refreshBody();
platforms.create(600, 535, 'ground2').setScale(0.6).refreshBody();
platforms.create(750, 535, 'ground2').setScale(0.6).refreshBody();
cursors = this.input.keyboard.createCursorKeys();
player = this.physics.add.sprite(100, 300, 'dude').setGravity(0, 300);
player.setCollideWorldBounds(true);
this.anims.create({
key: 'left',
frames: this.anims.generateFrameNumbers('dude', { start: 0, end: 3 }),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'turn',
frames: [ { key: 'dude', frame: 4 } ],
frameRate: 20
});
this.anims.create({
key: 'right',
frames: this.anims.generateFrameNumbers('dude', { start: 5, end: 8 }),
frameRate: 10,
repeat: -1
});
this.physics.add.collider(player, platforms);
info = this.add.text(10, 10, '', { font: '48px Arial', fill: '#ff0000' });
info3 = this.add.text(19, 50, '', { font: '48px Arial', fill: '#ff0000' });
timer2 = this.time.addEvent({ delay: 90000, callback: ganhar,callbackScope: this, });
timer1 = this.time.addEvent({ delay: 2000, callback: this.addRowOfPipes,callbackScope: this, loop: true });
},
update: function ()
{
if (cursors.left.isDown)
{
player.setVelocityX(-130);
player.anims.play('left', true);
}
else if (cursors.right.isDown)
{
player.setVelocityX(130);
player.anims.play('right', true);
}
else
{
player.setVelocityX(0);
player.anims.play('turn');
}
if (cursors.up.isDown)
{
player.setVelocityY(-250);
}
if (cursors.down.isDown)
{
player.setVelocityY(300);
}
info3.setText('Lifes: ' + vida);
info.setText('Time: ' + Math.floor(90000 - timer2.getElapsed()));
},
addOnePipe: function(x, y) {
pipe = this.physics.add.image(x, y, 'br').setScale(1.1);
pipe.setVelocityX(-150);
this.pipes.addMultiple(pipe);
pipe.checkWorldBounds = true;
pipe.outOfBoundsKill = true;
var collider= this.physics.add.overlap(player, pipe, perder, false, this);
},
addRowOfPipes: function() {
var hole = Phaser.Math.Between(1, 6);
//var hole=6;
for (var i = 0; i < 8; i++)
if (i != hole && i != hole + 1){
this.addOnePipe(760, i *54 + 40);
}
},
});
function perder(player,pipe)
{
vida--;
if (vida==0){
this.scene.start('gameover');
}
else(this.scene.start('game2'));
collider.active = false;
}
function ganhar ()
{
this.scene.start('gamewon2');
}
function collectStar (player, star)
{
star.disableBody(true, true);
drums.stop();
synth2.stop();
this.scene.start('gamewon');
}
function Gameover ()
{
drums.stop();
synth2.stop();
vida--;
if (vida==0){
this.scene.start('gameover');
}
else(this.scene.start('game'));
}
var GameWon = new Phaser.Class({
Extends: Phaser.Scene,
initialize:
function GameWon ()
{
Phaser.Scene.call(this, { key: 'gamewon' });
window.OVER = this;
},
create: function ()
{
music = this.sound.addAudioSprite('kyobi');
music.play('title');
var map2= this.add.image(400,300,'back');
this.add.sprite(580, 380, 'final').setScale(0.8);
var play4= this.add.image(151,481,'play').setScale(0.2);
this.add.text(96, 460, 'Map2', { font: '50px Courier', fill: '#000000' });
this.add.text(40, 30, 'Congratulations!!!', { font: '45px Arial', fill: '#ffffff' });
this.add.text(40, 100, 'You won Map 1.', { font: '39px Courier', fill: '#ffffff' });
this.add.text(40, 150, 'Try to beat the 2 Map.', { font: '39px Courier', fill: '#ffffff' });
play4.setInteractive();
play4.once('pointerup', function () {
music.stop();
this.scene.start('game2');
}, this);
}
});
var GameWon2 = new Phaser.Class({
Extends: Phaser.Scene,
initialize:
function GameWon2 ()
{
Phaser.Scene.call(this, { key: 'gamewon2' });
window.OVER = this;
},
create: function ()
{
var map3= this.add.image(400,300,'back');
this.add.sprite(580, 380, 'final').setScale(0.8);
var play6= this.add.image(151,481,'play').setScale(0.2);
this.add.text(96, 460, 'Menu', { font: '50px Courier', fill: '#000000' });
this.add.text(40, 30, 'Congratulations!!!', { font: '45px Arial', fill: '#ffffff' });
this.add.text(40, 100, 'You won Map 2.', { font: '39px Courier', fill: '#ffffff' });
this.add.text(40, 150, 'More maps coming soon.Be Aware', { font: '39px Courier', fill: '#ffffff' });
play6.setInteractive();
play6.once('pointerup', function () {
this.scene.start('mainmenu');
}, this);
}
});
var GameOver = new Phaser.Class({
Extends: Phaser.Scene,
initialize:
function GameOver ()
{
Phaser.Scene.call(this, { key: 'gameover' });
window.OVER = this;
},
create: function ()
{
var back= this.add.image(400,300,'back');
this.add.sprite(397.5, 230, 'imgfinal').setScale(0.75);
var play5= this.add.image(395,508,'play').setScale(0.22);
this.add.text(311, 490, 'Restart', { font: '40px Courier', fill: '#000000' });
play5.setInteractive();
play5.once('pointerup', function () {
this.scene.start('mainmenu');
}, this);
}
});
var config = {
type: Phaser.AUTO,
width: 800,
height: 600,
parent: 'phaser-example',
physics: {
default: 'arcade',
arcade: {
debug: false
}
},
scene: [ Preloader, MainMenu, Game, Game2, Rules, GameOver,GameWon, GameWon2 ]
};
var synth2;
var drums;
var music;
var vida=3;
var game = new Phaser.Game(config);
var blocked = false;

Related

how to set character frame of spritesheet in phaser js?

how to set frame of character?
here is my code
this.load.spritesheet(`dude-1`, `../src/assets/Character/ch-1.png`, {
frameWidth: 72,
frameHeight: 92,
});
main logic code is here
this.player = this.physics.add.sprite(100, -500, this.charSelect).setOrigin(1, 1);
this.player.body.setGravityY(1700);
this.player.setBounce(0.1);
this.physics.add.existing(this.player).body.setSize(15, 90, ).setOffset(20, 0)
this.anims.create({
key: "left",
frames: this.anims.generateFrameNumbers(this.charSelect, { start: 6, end: 10 }),
frameRate: 10,
repeat: -1,
});
this.anims.create({
key: "turn",
frames: [{ key: this.charSelect, frame: 5 }],
frameRate: 10,
});
this.anims.create({
key: "right",
frames: this.anims.generateFrameNumbers(this.charSelect, { start: 0, end: 4 }),
frameRate: 10,
repeat: -1,
});
cursors = this.input.keyboard.createCursorKeys();
this.physics.add.collider(this.player, this.platformGroup);
this.player.body.setCollideWorldBounds(true);
this.physics.world.setBounds(0, 0, (config.width) - 10, config.height, true, true, false, true);
here is output and issue. how to set the frame of character?
The problem is, that the phaser-image / frame size is too big (or the actual image is to small). Check the frame size (frameWidth and frameHeight) and the actual image size, that could solve your problem.
Here a short demo:
It loads the same spritesheet, once with the correct frameWidth / frameHeight size and once with a too big size.
document.body.style = `padding:0;margin:0;`;
class Example extends Phaser.Scene {
constructor() {
super();
}
preload() {
this.load.spritesheet('mummyCorrectSize', 'https://labs.phaser.io/assets/animations/mummy37x45.png', { frameWidth: 37, frameHeight: 45 });
this.load.spritesheet('mummyWrongSize', 'https://labs.phaser.io/assets/animations/mummy37x45.png', { frameWidth: 50, frameHeight: 50 });
}
create(){
// the "const" variables show the the wrong and right sprite creation
const wrongSizeSprite= this.add.sprite(50, 40, 'mummyCorrectSize').setOrigin(0);
const rightSizeSprite = this.add.sprite(50, 120, 'mummyWrongSize').setOrigin(0);
this.add.text(50, 10, 'Right size: single sprite/frame shown');
this.add.text(50, 100, 'Wrong size: the whole image is shown');
}
}
const config = {
type: Phaser.AUTO,
width: 500,
height: 180,
scene: [ Example ]
};
new Phaser.Game(config);
<script src="//cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>

How to use Chart.js in Nodejs?

How to create a pie chart using NodeJs with chartjs?
want to create different types of charts using chartjs but when I tried to run the code shows "cannot set the property of width"
TypeError: Cannot set property 'width' of undefined
at ni.resize (node_modules\chart.js\dist\Chart.min.js:7:93312)
at ni.initialize (node_modules\chart.js\dist\Chart.min.js:7:92818)
at ni.construct (node_modules\chart.js\dist\Chart.min.js:7:92559)
at new ni (node_modules\chart.js\dist\Chart.min.js:7:91964)
at Object.<anonymous> (chartjs\chart.js:7:15)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
I tried to run this code to produce a pie chart image but found this error.
let Canvas = require("canvas"),
canvas = Canvas.createCanvas(400, 400),
ctx = canvas.getContext("2d"),
Chart = require('chart.js'),
fs = require("fs");
var myChart = new Chart(ctx, {
type: "pie",
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: "# of Votes",
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
"rgba(255, 99, 132, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(255, 206, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(255, 159, 64, 0.2)"
],
borderColor: [
"rgba(255, 99, 132, 1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)",
"rgba(75, 192, 192, 1)",
"rgba(153, 102, 255, 1)",
"rgba(255, 159, 64, 1)"
],
borderWidth: 1
}
]
},
options: {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true
}
}
]
}
}
});
canvas.toBuffer(function(err, buf) {
if (err) throw err;
fs.writeFileSync("chart.png", buf);
});
Should be an image in the current folder
I suggest using ChartJS for Node: https://www.npmjs.com/package/chartjs-node
It draws a chart which you can then save to the file system and insert accordingly.
Here's a snippet of code as an example:
import * as ChartjsNode from 'chartjs-node'; // Import the library
const chartNode = new ChartjsNode(600, 600); // Create an instance with dimensions
const barGraphOptions = {
type: 'bar',
data: []
};
// Draw the chart and write the file to the file system
await new Promise(resolve => {
chartNode
.drawChart(barGraphOptions)
.then(() => {
chartNode.getImageBuffer('image/png');
})
.then(() => {
chartNode.writeImageToFile('image/png', 'some_file.png').then(() => {
resolve();
});
})
.catch(e => {
console.log('Caught', e);
});
});
ChartJS is an HTML5 based file which is used in front-end development only.
For more information visit this site.
You can refer to this answer if you want to use nodejs to create Charts.
P.S. This question is duplicate to this
I had the same issue as OP. I couldn't figure out a way to do it using the standard approach of combining Node Canvas and Chart.JS, but I found using ChartjsNodeCanvas works.
import { CanvasRenderService } from 'chartjs-node-canvas';
canvasRenderService: CanvasRenderService;
async createGraph(data: any) {
const configuration = {
type: 'bar',
data: {
labels: // Your labels,
datasets: [
data
]
},
options: {
// Your options
}
};
const canvasRenderService = new CanvasRenderService(300, 500);
return await canvasRenderService.renderToDataURL(configuration);
// or return canvasRenderService.renderToBuffer(configuration);
// or return canvasRenderService.renderToStream(configuration);
}
await this.createGraph(data);
Note, ChartjsNodeCanvas requires ChartJS as a dependency.

syntax to loop through docs send from express router and use it to plot chart js

I am starting to learn node js (express js). I am trying to plot a chart using data sent from the mongo db using mongoose....I would want to loop the docs sent from the database to be used in ploting the data. I had tried using fetch api but it failed due to Passport req.user (it didn't recognize user )
here is my code. I will appreciate for any help and leads.
router.get('/mychart', loggedInYes, function (req, res, next) {
Products.find({user:req.user._id},function (err,docs) {
if (err)
return err;
res.render('user/mychart',{docs:docs});
});
});
and here is the chart js where I would want to use Docs
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [{
{#
each docs
}
} {
{
this.docs.yearofbirth
}
} {
{
/each}}],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
The problem is how to loop through the data....data: [{
{#
each docs
}
} {
{
this.docs.yearofbirth
}
} {
{
/each}}],
I solved it by including the credentials objects in the client hbs file. It worked
fetch('/api/foo', {credentials: 'include'})

Error ReferenceError: CanvasGradient is not defined

I am trying to create a line chart using chartjs-node package. Below is the code. When I give the data of dataset as a small set like data: [20, 15, 60, 60, 65, 30, 70], it works fine. But if I change it to a list that I want to populate as in dataFirst dataset below, I get the error "ReferenceError: CanvasGradient is not defined". I donot understand the reason. Please help. Thanks.
public createChart(cData) {
const chartNode = new chart(1000, 800);
const dataFirst = {
label: 'Heat Sink',
data: cData,
lineTension: 0.3,
fill: false,
borderColor: 'red',
backgroundColor: 'transparent',
pointBorderColor: 'red',
pointBackgroundColor: 'lightgreen',
pointRadius: 5,
pointHoverRadius: 15,
pointHitRadius: 30,
pointBorderWidth: 2,
pointStyle: 'rect',
};
const dataSecond = {
label: 'TVK Channel 9',
data: [20, 15, 60, 60, 65, 30, 70],
lineTension: 0.3,
fill: false,
borderColor: 'purple',
backgroundColor: 'transparent',
pointBorderColor: 'purple',
pointBackgroundColor: 'lightgreen',
pointRadius: 5,
pointHitRadius: 30,
pointBorderWidth: 2,
};
const chartOptions = {
legend: {
display: true,
position: 'top',
labels: {
boxWidth: 80,
fontColor: 'black',
},
},
};
const speedData = {
labels: ['0s', '10s', '20s', '30s', '40s', '50s', '60s'],
datasets: [dataFirst, dataSecond],
};
const chartJsOptions = {
type: 'line',
data: speedData,
options: chartOptions,
};
I found the solution. The number of labels should match the number of data points.
In canvas for node implementation you need to export CanvasGradient class yourself. According to this issue: https://github.com/Automattic/node-canvas/issues/990
You can do this:
["CanvasRenderingContext2D", "CanvasPattern", "CanvasGradient"].forEach(obj => {
console.log(obj, canvas[obj])
global[obj] = canvas[obj]
})

multiple tween on single node kinetic.js

I have a bar diagram for a polling system.i want two transition(tween) effects on events they are following
Mouse over OR check box check
Click button
I am using the same node for tween.tween.play() is working fine but on reverse the y cordinate that i gave in tween constructor not working.
checkout my jsfiddle
var stagewidthbywindow = 1000;
var stagesetting = {
container: "container_1_1_0",
width: stagewidthbywindow,
height: 50
};
var rectwidth0 = 0;
var rectSum = 0;
var stage110 = new Kinetic.Stage(stagesetting);
var layer110 = new Kinetic.Layer();
var group110 = new Kinetic.Group();
layer110.add(group110);
function increasestage() {
var myChecker = setInterval(function () {
var stage_height = stage110.getHeight();
if (stage_height == 250) {
clearInterval(myChecker);
} else {
stage110.setAttr("height", stage_height + 2.5);
}
}, 10);
}
var rectwidth1 = stagesetting.width * 0.5;
rectSum += rectwidth0;
var rectObject1 = {
x: rectSum,
y: 0,
width: rectwidth1,
height: 50,
fill: "#DA4B4B",
stroke: "#ffffff",
strokeWidth: 2,
opacity: 1
};
var shadeObject = {
x: rectSum,
y: 0,
width: stagewidthbywindow,
height: 50,
fill: "#f3f3f3",
stroke: "#f3f3f3",
strokeWidth: 1,
opacity: 1
};
var shade111 = new Kinetic.Rect(shadeObject);
var rect111 = new Kinetic.Rect(rectObject1);
rectSum += rectwidth1;
var ansOption111 = new Kinetic.Text({
x: rect111.getX() + 10,
y: rect111.getY() + 10,
text: "iPhone 5s",
fontSize: 14,
fontFamily: "Merriweather Sans",
width: rect111.getWidth(),
align: "left",
fill: "#ffffff"
});
var ansPercentage111 = new Kinetic.Text({
x: rect111.getX() + 10,
y: 30,
text: "50%",
fontSize: 15,
fontFamily: "Merriweather Sans",
width: rect111.getWidth(),
fontStyle: "bold",
align: "left",
fill: "#ffffff"
});
group110.add(shade111);
group110.add(rect111);
group110.add(ansOption111);
group110.add(ansPercentage111);
rect111.tween = new Kinetic.Tween({
node: rect111,
scaleX: 1,
scaleY: 5,
easing: Kinetic.Easings.Linear,
duration: .5
});
ansOption111.tween = new Kinetic.Tween({
node: ansOption111,
scaleX: 1.5,
scaleY: 1.5,
x: rect111.getX() + 20,
y: 20,
easing: Kinetic.Easings.Linear,
duration: .5,
});
ansPercentage111.tween = new Kinetic.Tween({
node: ansPercentage111,
x: rect111.getX() + 20,
y: 100,
scaleX: 3,
scaleY: 3,
easing: Kinetic.Easings.Linear,
duration: .5,
});
rect111.on("mouseover touchstart", function (evt) {
if (!$("#sample_size1").is(":checked") &&
$("#orientation_1_1_0").val() == "horizontal") {
stage110.setAttr("height", 250);
rect111.tween.play();
ansOption111.tween.play();
ansPercentage111.tween.play();
}
});
rect111.on("mouseout touchend", function (evt) {
if (!$("#sample_size1").is(":checked") &&
$("#orientation_1_1_0").val() == "horizontal") {
stage110.setAttr("height", 50);
rect111.tween.reverse();
ansOption111.tween.reverse();
ansPercentage111.tween.reverse();
}
});
ansOption111.on("mouseover touchstart", function (evt) {
if (!$("#sample_size1").is(":checked") &&
$("#orientation_1_1_0").val() == "horizontal") {
stage110.setAttr("height", 250);
rect111.tween.play();
ansOption111.tween.play();
ansPercentage111.tween.play();
}
});
ansOption111.on("mouseout touchend", function (evt) {
if (!$("#sample_size1").is(":checked") &&
$("#orientation_1_1_0").val() == "horizontal") {
stage110.setAttr("height", 50);
rect111.tween.reverse();
ansOption111.tween.reverse();
ansPercentage111.tween.reverse();
}
});
$("#sample_size1").change(function () {
if ($(this).is(":checked") && $("#orientation_1_1_0").val() == "horizontal") {
var scaleFactor = 5;
increasestage();
stage110.draw();
rect111.tween.play();
ansOption111.tween.play();
ansPercentage111.tween.play();
} else if (!$(this).is(":checked") && $("#orientation_1_1_0").val() == "horizontal") {
rect111.tween.reverse();
ansOption111.tween.reverse();
ansPercentage111.tween.reverse();
setTimeout(function () {
stage110.setAttr("height", 50);
}, 600);
}
});
var rectangle111 = new Kinetic.Tween({
node: rect111,
duration: .5,
x: 0,
y: 20 * 1 + 18 * 0,
width: rectwidth1,
height: 20,
opacity: 1,
scaleX: 1
//scaleY: 0.4
});
var shadetween111 = new Kinetic.Tween({
node: shade111,
duration: .5,
x: 0,
y: 20 * 1 + 18 * 0,
//width: stagewidthbywindow,
height: 20,
opacity: 1,
scaleX: 1
});
var answerOption111 = new Kinetic.Tween({
node: ansOption111,
duration: .5,
x: 0,
y: (40 * 0),
width: 150,
height: 15,
opacity: .9,
strokeWidth: 2,
scaleX: 1
});
function call_answerPercentage111() {
var answerPercentage111 = new Kinetic.Tween({
node: ansPercentage111,
x: 160,
y: (40 * 0),
width: 150,
height: 18,
opacity: .9,
duration: 0.5,
strokeWidth: 2,
scaleX: 1
});
return answerPercentage111;
}
document.getElementById("arrow110").addEventListener("click", function () {
if ($("#orientation_1_1_0").val() == "horizontal") {
$("#arrow110").addClass("btn-arow-down");
stage110.setAttr("height", 4 * 40);
$("#orientation_1_1_0").val("vertical");
if ($("#sample_size1").is(":checked")) {
console.log("destroy");
}
ansPercentage111.setFill("black");
ansOption111.setFill("black");
rectangle111.play();
shadetween111.play();
answerOption111.play();
var answerPercentage111 = call_answerPercentage111();
answerPercentage111.play();
layer110.draw();
} else if ($("#orientation_1_1_0").val() == "vertical") {
$("#arrow110").removeClass("btn-arow-down");
$("#orientation_1_1_0").val("horizontal");
ansPercentage111.setFill("white");
ansOption111.setFill("white");
rectangle111.reverse();
shadetween111.reverse();
answerOption111.reverse();
var answerPercentage111 = call_answerPercentage111();
answerPercentage111.reverse();
answerPercentage111.destroy();
layer110.draw();
setTimeout(function () {
stage110.setAttr("height", 50);
}, 1000);
}
}, false);
stage110.add(layer110);
On calling call_answerPercentage111 you are creating new tween. You can not reverse tween that is not played with play() function. Also you are calling destroy() method after reverse() - you can do this ONLY after tween is done (or you will stop the tween).
http://jsfiddle.net/ynNUN/3/

Resources