Phaser // Javascript // Player is not defined - javascript

Everything is working, except in the update function, when I put back the var player, it doesn't recognize it:
"Uncaught ReferenceError: player is not defined"
(I'm also not sure for the animation) (Mario is the player, it's a mario level)
Here is my code:
var SandBox = {
preload:function(){
//this.game
console.log("preload Sand Box");
this.game.load.image('platform', 'assets/platform.png');
this.game.load.spritesheet('mario', 'assets/mario.png', 32, 32 , 12);
this.game.load.image('coinbox', 'assets/coinbox.png');
},
create:function(){
console.log("create Sand Box");
var imageHeight = this.game.cache.getImage("platform").height;
this.game.physics.startSystem(Phaser.Physics.ARCADE);
var worldHeight = this.game.world.height;
var ground = this.game.add.sprite(0, worldHeight - imageHeight, 'platform');
var platform = this.game.add.sprite(250, 285, 'platform');
var platform = this.game.add.sprite(-250, 145, 'platform');
var platform = this.game.add.sprite(280, 285, 'coinbox');
var player = this.game.add.sprite(32, 100, 'mario');
this.game.physics.enable(ground);
this.game.physics.enable(platform);
this.game.physics.arcade.enable(player);
player.frame = 5;
ground.body.immovable = true;
platform.body.immovable = true;
player.body.bounce.y = 0.2;
player.body.gravity.y = 300;
player.body.collideWorldBounds = true;
player.animations.add('left', [0, 1, 2, 3], 10, true);
player.animations.add('right', [5, 6, 7, 8], 10, true);
},
update:function(){
console.log("update Sand Box");
this.game.physics.arcade.enable(player);
var hitPlatform = this.game.physics.arcade.collide(player, ground); // << THESE FUNCTIONS
}
}

The scope of variable player in thr snippet is local to the function it is in. One can move the declaration (with var) for player outside of the sandbox object:
var player;
var sandbox = {
create: function() {
//... skipping lines ...
player = this.game.add.sprite(32, 100, 'mario');
},
Update: function() {
//use player here
var hitPlatform = this.game.physics.arcade.collide(player, ground); // << THESE FUNCTIONS
}
};
Or make it part of the object:
var sandbox = {
create: function() {
//... skipping lines ...
this.player = this.game.add.sprite(32, 100, 'mario');
},
Update: function() {
//... skipping lines ...
//use this.player here
var hitPlatform = this.game.physics.arcade.collide(this.player, ground);
}
};

Related

How to spawn collectables or pickups in patterns and at random positions using Phaser 3

I am Making a 2d endless runner using Phaser 3 and I need to spawn coins and other pickups in random positions and also in different patterns such as diamond shape, square,...
I don't really have much code and I do not know how to go about it. I would gladly appreciate any help in any way. Thank you.
It depends on your code-structure, but I would use the builtin function Phaser.Math.Between, to generate random positions/numbers (link to the documentation).
(Sidenote: The first examples are made for arcade physics, the final one with is made for matter.js )
Here is a very simple approach:
In code:
The interval in which coins are spawned is random
setTimeout(_ => this.loadCoins(coins), Phaser.Math.Between(2500, 3000));
The position of the pickup is random
let yCoord = Phaser.Math.Between(20, 180);
let xCord = 400 + Phaser.Math.Between(0, 100);
The pickup type is random
let coinType = Phaser.Math.Between(0, 2);
and te amount of coins to spawn
let coinsToSpawn = Phaser.Math.Between(1, 5);
class GameScene extends Phaser.Scene {
constructor() {
super({ key: 'GameScene' });
}
loadCoins(coins){
let coin;
// Generate random amount of coins each time
let coinsToSpawn = Phaser.Math.Between(1, 5);
for(let i = 0; i < coinsToSpawn; i++){
// Get Random y position (x is always bigger than the scene width)
let yCoord = Phaser.Math.Between(20, 180);
let xCord = 400 + Phaser.Math.Between(0, 100);
// Randomly generate types
let coinType = Phaser.Math.Between(0, 2);
switch(coinType){
case 0:
coin = this.add.rectangle(xCord, yCoord, 15, 15, 0xFFFF00);
break;
case 1:
coin = this.add.circle(xCord, yCoord, 7, 0xFF0000);
break;
case 2:
coin = this.add.star(xCord, yCoord, 5, 5, 15, 0x00FF00);
break;
}
coin = this.physics.add.existing(coin);
coins.add(coin);
}
coins.setVelocityX(-100);
// Start next Coin loading randomly in 2.5 - 3 Seconds
setTimeout(_ => this.loadCoins(coins), Phaser.Math.Between(2500, 3000));
}
create() {
this.player = this.add.rectangle(200, 100, 20, 20, 0xffffff);
this.physics.add.existing(this.player);
//Add World Physics
this.physics.world.setBounds(0, 0, 400, 200);
this.player.body.setCollideWorldBounds(true);
this.player.body.setImmovable(true);
let coins = this.physics.add.group({immovable: true, allowGravity: false});
this.loadCoins(coins);
this.physics.add.collider(this.player, coins,
(player, coin) => {
coin.destroy();
});
}
}
const config = {
type: Phaser.AUTO,
width: 400,
height: 200,
scene: [ GameScene ],
physics: {
default: 'arcade',
}
};
const game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>
Update (create shapes with coins):
-> Check out some cool builtin functions in the Phaser.Actions Namespace (like to the documentation).
like _(to name a few)):
Phaser.Actions.PlaceOnCircle
Phaser.Actions.PlaceOnLine
Phaser.Actions.PlaceOnTriangle
...
Disclaimer: This code is not optimal is just created like this to proof the point.
UPDATE for spawning:
Sidenotes:
the spawn has to be trigger, so I use setInterval, but you can use events, user input, or simply in the update function, or ...
the cleanup and the saving of the groups could be handled better, but it's a demo.
class GameScene extends Phaser.Scene {
constructor() {
super({ key: 'GameScene' });
//keep reference to the groups
this.coinGroups = [];
}
spawnCoins(){
let coins = this.physics.add.group({immovable: true, allowGravity: false});
var circle = new Phaser.Geom.Circle(440, 80, 40);
for(let i = 0; i < 10; i++){
let coin = this.add.circle(0, 0, 8, 0xFFFF00);
coin = this.physics.add.existing(coin);
coins.add(coin);
}
coins.setVelocityX(-100);
this.coinGroups.push(coins);
Phaser.Actions.PlaceOnCircle(coins.getChildren(), circle);
}
create() {
this.add.text(10,10,'Spawing every 2sec')
.setColor('#ffffff');
// Spawing ever 2 Sec
setInterval( _ => {
this.spawnCoins();
}, 2000);
}
update(){
// Minor Cleanup
for(let group of this.coinGroups){
group.getChildren().forEach(child => {
if(child.x < 0){
group.remove(child, true, true);
}
});
}
this.coinGroups = this.coinGroups.filter(group => group.length > 0 );
}
}
const config = {
type: Phaser.AUTO,
width: 400,
height: 200,
scene: [ GameScene ],
physics: {
default: 'arcade',
}
};
const game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>
Mini demo with matter.js:
class GameScene extends Phaser.Scene {
constructor() {
super({ key: 'GameScene' });
//keep reference to the groups
this.coinGroups = [];
}
spawnCoins(){
// standart Phaser Group
let coins = this.add.group();
var circle = new Phaser.Geom.Circle(440, 80, 40);
for(let i = 0; i < 10; i++){
let coin = this.matter.add.image(50, 50, 'coin').setOrigin(.5);
coin.setIgnoreGravity(true);
coin.setVelocityX(-3);
coin.setFrictionAir(0);
coins.add(coin);
}
this.coinGroups.push(coins);
Phaser.Actions.PlaceOnCircle(
coins.getChildren(), circle);
}
create() {
this.add.text(10, 10, 'Coins spawned every second')
.setOrigin(0)
.setColor('#ffffff');
// Just creating a texture/image for matter
let g = this.make.graphics({x: 0, y: 0, add: false});
g.fillStyle(0xffff00);
g.fillCircle(7, 7, 7);
g.generateTexture('coin', 14, 14);
setInterval( _ => this.spawnCoins(), 1000);
}
update(){
// Clean Up
for(let group of this.coinGroups){
group.getChildren().forEach(child => {
if(child.x < 0){
group.remove(child, true, true);
}
});
}
this.coinGroups = this.coinGroups.filter(group => group.getChildren().length > 0);
}
}
const config = {
type: Phaser.AUTO,
width: 400,
height: 200,
scene: [ GameScene ],
physics: {
default: 'matter'
},
};
const game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>

multiple HTML5 canvas with Neurosky sensor input is not working

I have created multiple html5 canvas using instantiation mode in P5JS. I am using Neurosky mindwave EEG sensor to activate and deactivate canvas one by one. Neurosky mindwave EEG sensor can detect user's eye blink which I am using as input. When user blinks, it should activate one canvas and deactivate another canvas and vice-versa.I am using Neurosky mindwave EEG sensor to activate and deactivate canvas one by one. Neurosky mindwave EEG sensor can detect user's eye blink which I am using as input. When user blinks, it should activate one canvas and deactivate another canvas and vice-versa.
Just to check if my code logic works, I used mouse pressed input to switch between the canvas and it worked perfectly. But, when I used it with the sensor it didn't work.
What I did - I have created multiple HTML5 canvas using instantiation mode in P5JS. I have used node-neurosky node module to capture the eyeblink data from the sensor. Node Module
What worked - When I launch the app it takes the eye blink as input for the first time and activate the another canvas but when I blink again it doesn't deactivate the current canvas and activate another canvas. I have tried printing flags to check the code and it is doing fine. Eyeblink gets detected every time when I blink but it doesn't switch the canvas.
What didn't work - When I tried to use eye blink strength directly into the sketch.js it didn't work then I created another boolean variable eyeclick which also didn't work.
sketch.js
var stateTwo, stateOne = true;
// sketch one -----------------------------------
var first = new p5(firstSketch, "canvasOne");
function firstSketch(p) {
p.setup = function() {
p.createCanvas(400, 250);
}
p.draw = function() {
p.background(255, 10, 100);
p.fill(255);
p.ellipse(p.width / 2, p.height / 2, 50, 50);
if (eyeclicked) {
stateOne = false;
stateTwo = true;
console.log(" canvas <-- one");
// k = 0;
eyeclicked = false;
}
if (stateOne) {
$('#canvasOne').css('opacity', '1');
$('#canvasTwo').css('opacity', '0.5');
// console.log("canvas One");
p.fill(255, 0, 0);
p.ellipse(p.random(p.width), p.random(p.height), 50, 50);
}
}
}
// sketch two -----------------------------------
var second = new p5(secondSketch, "canvasTwo");
function secondSketch(p) {
p.setup = function() {
p.createCanvas(400, 250);
}
p.draw = function() {
p.background(60, 250, 100);
p.fill(0);
p.ellipse(p.width / 2, p.height / 2, 50, 50);
if (eyeclicked) {
stateOne = true;
stateTwo = false;
console.log(" canvas <-- two");
// k = 0;
eyeclicked = false;
}
if (stateTwo) {
$('#canvasOne').css('opacity', '0.5');
$('#canvasTwo').css('opacity', '1');
// console.log("canvas Two");
p.fill(0, 0, 255);
p.ellipse(p.random(p.width), p.random(p.height), 50, 50);
}
}
}
NodeCode to connect with sensor connect.js
var attention = 0;
var meditation = 0;
var blink;
var poorSignalLevel = 0;
var eyeclicked = false;
if ("WebSocket" in window) {
console.log("WebSocket is supported by your Browser. Proceed.");
// $('#connect-controls').show();
}
var ws = new WebSocket("ws://127.0.0.1:8080");
ws.onopen = function() {
console.log('opened connection');
ws.send("Hello from websocket client!");
};
// whenever websocket server transmit a message, do this stuff
ws.onmessage = function(evt) {
// parse the data (sent as string) into a standard JSON object (much easier to use)
var data = JSON.parse(evt.data);
// handle "eSense" data
if (data.eSense) {
$('#brain').css({
opacity: 1
});
attention = data.eSense.attention;
meditation = data.eSense.meditation;
// brainProgress('#focusProgress', attention);
// brainProgress('#medProgress', meditation);
$("#focus").text(attention);
$("#meditation").text(meditation);
}
// handle "blinkStrength" data
if (data.blinkStrength) {
blink = data.blinkStrength;
var blinkcol = "white";
var eyeVal = map_range(blink, 0, 255, 0, 100);
$('#eyeBlinkStrength').text(parseInt(eyeVal));
if (blink > 40) {
//blinkcol = "rgba(102,211,43,1.0)";
eyeclicked = true;
// k++;
console.log(blink + " " + eyeclicked);
} else blinkcol = "white";
$('#eyeBlink').css({
width: eyeVal,
height: eyeVal,
background: blinkcol
});
} else {
blink = 0;
eyeclicked = false;
}
// handle "poorSignal" data
if (data.poorSignalLevel != null) {
poorSignalLevel = parseInt(data.poorSignalLevel);
}
};
// when websocket closes connection, do this stuff
ws.onclose = function() {
// websocket is closed.
console.log("Connection is closed...");
};
function map_range(value, low1, high1, low2, high2) {
return low2 + (high2 - low2) * (value - low1) / (high1 - low1);
}
EDIT CODE PEN DEMO
Mouse Input Based Code which demonstrate the logic of switching between multiple canvas. It works perfectly. Try to click into the center circle
var stateTwo, stateOne = true;
var eyeIsBlinked;
// sketch one -----------------------------------
var first = new p5(firstSketch, "canvasOne");
function firstSketch(p) {
p.setup = function() {
p.createCanvas(400, 250);
}
p.draw = function() {
p.background(255, 10, 100);
p.fill(255);
p.ellipse(p.width / 2, p.height / 2, 50, 50);
if (p.mouseIsPressed && p.dist(p.mouseX, p.mouseY, p.width / 2, p.height / 2) < 50) {
stateOne = false;
stateTwo = true;
console.log(" <-- one");
// k = 0;
// window.eyeIsBlinked = false;
// blink = 0;
}
if (stateOne) {
$('#canvasOne').css('opacity', '1');
$('#canvasTwo').css('opacity', '0.5');
// console.log("canvas One");
p.fill(255, 0, 0);
p.ellipse(p.random(p.width), p.random(p.height), 50, 50);
}
}
}
// sketch two -----------------------------------
var second = new p5(secondSketch, "canvasTwo");
function secondSketch(p) {
p.setup = function() {
p.createCanvas(400, 250);
}
p.draw = function() {
p.background(60, 250, 100);
p.fill(0);
p.ellipse(p.width / 2, p.height / 2, 50, 50);
if (p.mouseIsPressed && p.dist(p.mouseX, p.mouseY, p.width / 2, p.height / 2) < 50) {
stateOne = true;
stateTwo = false;
console.log(" <-- two");
// k = 0;
// window.eyeIsBlinked = false;
//blink = 0;
}
if (stateTwo) {
$('#canvasOne').css('opacity', '0.5');
$('#canvasTwo').css('opacity', '1');
// console.log("canvas Two");
p.fill(0, 0, 255);
p.ellipse(p.random(p.width), p.random(p.height), 50, 50);
}
}
}
I don't know how your project works. But I guess the problem might be a scope problem. Both files are using the eyeclicked variable, but they might be using two different variables. Try to make sure that they're using the same variable by using it inside the window global variable.
So instead of eyeclicked use window.eyeclicked.

Phaser game getting slow [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Fist time i am using phaser.io, i am repeating background and also loading other thing in update function but after few second later my game is slowing time . it look like background is not moving more. Please have a look of my code and help me in for sort out this problem. Or please give any idea to change background repeatedly without changing other thing.
I have some code indentation problem sorry for that but please try to manage and help me.
Game.js
var scoreTxt, score, speed, scoreTextValue, ques_label, ques_label_pizza, scoreTextKey, timerTextValue, timerTextKey, textStyle_Key, textStyle_Value, anscloud, astroid1, astroid2, astroid3, astroid4;
/*var gameType;*/ //Pizza or Noun
var bullets, quesTextValue, ansTextValue, sprite;
var fireRate = 100;
var nextFire = 0;
var xAxis = [];
var yAxis = [];
var tempQues = [];
var tempAns = [];
var result = [];
var answear = [];
var ques = [];
var astroidContains = [];
var astroidContainsText = []; //['right', 'wrong', 'wrong', 'wrong']
var astroid, spaceShip, quesbar, diamond, randomAnsPosition;
var s1Copy;
var cloudContains = []; //['noun', 'pronoun', 'pronoun']
var QbarContainsQue = [];
var ans,rightans;
var isAnswerCorrect = false;
var allowClick = false;
var spaceShipXAxis = 40, loader1Width = 85, loader2Width = 70;
var bar, loader1, loader2, timer, timerSprite, timerSpriteCount = 0;
var timerCounter = 45; //timer counter will be of 45 seconds.
//var timerCounter_ = 100; //timer counter will be of 45 seconds.
var questCounter = 0; //question counter no. of question played.
var maxQuest = 10;//max questions will be displayed is 10.
var diamondTextColor = "#8D4FA8";
var defTextColor = "#5BEFFE";
var ansTextColor = "#9E13DA";
var errTextColor = '#FF0000';
var corrTextColor = '#228B22';
var corr_ans_fst;
var corr_ans_sec;
var fun_bckg, randQues;
var wrong_ans;
var barre1_x = 150;
var barre1_y = 115;
var healthValue = 100;
var x_loader = 180;
var check =0;
var setAns = [];
var setOne = [['12+16=','28'], ['15+11=','26'], ['16+22=','38'], ['13+14=','27'], ['15+24=','39'], ['14+12=','26'], ['10+17=','27'], ['11+11=','22'],
['13+15=','28'], ['12+21=','33'], ['24+13=','37'], ['33+21=','54'], ['40+18=','58'], ['34+31=','65'], ['25+42=','67'], ['22+15=','37'],
['24+12=','36'], ['20+15=','35'], ['25+14=','39'], ['21+21=','42'], ['41+25=','66'], ['53+24=','77'], ['35+31=','66'], ['62+37=','99'],
['54+35=','89']];
var setTwo = [['15+18=','33'], ['17+17=','34'], ['13+19=','32'], ['18+14=','32'], ['15+27=','42'], ['18+17=','35'], ['27+29=','56'], ['23+28=','51'],
['36+37=','73'], ['45+25=','70'], ['46+45=','91'], ['38+57=','95'], ['49+43=','92'], ['37+53=','90'], ['48+33=','81']];
var Game = {
preload : function() {
// Load the needed image for this(play) game screen.
//load the menu screen
this.load.image('menu', './assets/images/menu.png');
// Here we load all the needed resources for the level.
// background image screen
this.load.image('playgame', './assets/images/back.png');
// globe image screen
this.load.image('playgame', './assets/images/back.png');
// win image screen
//this.load.image('win', './assets/images/win.png');
// spaceship image screen
this.load.image('spaceship', './assets/images/spaceship.png');
// Question bar image screen
this.load.image('quesbar', './assets/images/quesbar.png');
// Diamond image screen
this.load.image('diamond', './assets/images/diamond.png');
// Astroid image screen
this.load.image('astroid1', 'assets/images/asteroid1.png');
this.load.image('astroid2', 'assets/images/asteroid2.png');
this.load.image('astroid3', 'assets/images/asteroid3.png');
this.load.image('astroid4', 'assets/images/asteroid4.png');
// Loader image screen
this.load.image('loaderbck', 'assets/images/loaderbck.png');
this.load.image('loader1', 'assets/images/loader1.png');
this.load.image('loader2', 'assets/images/loader2.png');
//Load the bullet
this.load.image('bullet', 'assets/images/bullet.png');
},
create : function() {
// By setting up global variables in the create function, we initialise them on game start.
// We need them to be globally available so that the update function can alter them.
textStyle_Value = { font: "bold 20px Segoe UI", fill: defTextColor, align: "center" };
textStyleAns = { font: "bold 22px 'Comic Sans MS', 'Comic Sans'", fill: ansTextColor, wordWrap: true, wordWrapWidth: 10, align: "center"};
textStyleQues = { font: "bold 20px 'Comic Sans MS', 'Comic Sans'", fill: defTextColor, wordWrap: true, wordWrapWidth: 10, align: "center"};
sprite = game.add.sprite(310, 485, 'spaceship');
sprite.anchor.set(0.5);
// Loading backround image
this.playBackground();
this.playBackground1();
// Additional Sprites, like cloud
this.addSprites();
// Loading spaceship image
//this.spaceship();
// Loading questionbar image
this.questionbar();
// Call fun. for ques
this.comeQus();
// csll fun. for place astroid
// this.astroid();
// call fun. for Ans
this.generateQues();
this.generateAns();
// Loading Diamond image
this.diamond();
// Start timer
this.startTimer();
// Set timer.
this.setTimer();
this.initLoader();
},
update: function() {
// The update function is called constantly at a high rate (somewhere around 60fps),
// updating the game field every time - also destroying previous objects and creating new.
// Our bullet group
//bullets.destroy();
sprite.destroy();
bullets = game.add.group();
bullets.enableBody = true;
bullets.physicsBodyType = Phaser.Physics.ARCADE;
bullets.createMultiple(200, 'bullet', 100, false);
bullets.setAll('anchor.x',0);
bullets.setAll('anchor.y', 0.9);
bullets.setAll('outOfBoundsKill', true);
bullets.setAll('checkWorldBounds', true);
//Repeating background..
if(playgame != null && playgame.body.y > 600) {
playgame.destroy();
this.playBackground();
}
if(playgame1.body.y > 0) {
playgame1.destroy();
this.playBackground1();
this.initLoader();
}
if(astroid1 != undefined) astroid1.destroy();
if(astroid2 != undefined) astroid2.destroy();
if(astroid3 != undefined) astroid3.destroy();
if(astroid4 != undefined) astroid4.destroy();
this.addSprites();
//timerTextValue.text = "00:" + timerCounter;
this.initLoader();
//destroing old diamond obj and creating new while change background
//diamond.destroy();
this.diamond();
//destroing old questionbar obj and creating new while change background
quesbar.destroy();
this.questionbar();
//Call comeQus, comeAns for show ques and ans at every background change
// quesTextValue.destroy();
if(quesTextValue != undefined) quesTextValue.destroy();
this.comeQus();
//ansTextValue.destroy();
if(ansTextValue != undefined) ansTextValue.destroy();
this.comeAns();
if (game.input.activePointer.isDown) {
this.fire();
}
allowClick = true;
},
playBackground: function() {
// console.log("playBackground called");
playgame = this.add.sprite(0, 0, 'playgame', 5);
playgame.scale.set(1);
playgame.smoothed = false;
anim_playgame = playgame.animations.add('walk');
anim_playgame.play(10, true);
this.physics.enable(playgame, Phaser.Physics.ARCADE);
playgame.body.velocity.y = 50;
},
playBackground1: function() {
//console.log("playBackground1 called");
//Second background..
playgame1 = this.add.sprite(0, -600, 'playgame', 5);
playgame1.scale.set(1);
playgame1.smoothed = false;
anim_playgame1 = playgame1.animations.add('walk');
anim_playgame1.play(10, true);
this.physics.enable(playgame1, Phaser.Physics.ARCADE);
playgame1.body.velocity.y = 50;
},
questionbar: function() {
quesbar = game.add.image(10, 530, 'quesbar');
},
diamond: function() {
diamond = game.add.image(680, 20, 'diamond');
},
addSprites: function() {
// loading answer cloud
astroid1 = this.add.button(30, 90, 'astroid1', this.astroidClicked, this);
astroid2 = this.add.button(220, 30, 'astroid2', this.astroidClicked, this);
astroid3 = this.add.button(400, 40, 'astroid3', this.astroidClicked, this);
astroid4 = this.add.button(600, 90, 'astroid4', this.astroidClicked, this);
},
inCorrectAnswerHit: function(index) {
allowClick = false;
isAnswerCorrect = false;
//this.playFx('wrong_ans');
for(i=0; i<=3; i++) {
if(cloudContains[i] == "right") {
//cloudContainsText[i].fill = corrTextColor;
console.log("right ans hit");
break;
}
}
},
checkAnswer: function(index) {
// If clicked Ans is right so astroid will destroy.
if(astroidContainsText[index] == "wrong") {
//Here collization function will call
isAnswerCorrect = true;
}
// If clicked word is noun (correct answer) and obstacle is redbird or blackbird - the dude will slide.
else {
this.inCorrectAnswerHit(index);
}
},
generateQues: function(){
var que;
// Generating random questions from given list of ques - setOne.
s1Copy = setOne.slice();
//var result = [];
for (var i = 0; i < 3; i++) {result.push(s1Copy.splice(~~(Math.random()*s1Copy.length),1)[0]);}
s1Copy.push(...setTwo);
for (var i = 0; i < 7; i++) {result.push(s1Copy.splice(~~(Math.random()*s1Copy.length),1)[0]);}
result.toString();
for(var i = 0; i < result.length ; i++ ) {
que = result[i];
ques.push(que[0]);
ques.toString();
//console.log(ques);
answear.push(que[1]);
}
},
comeQus: function() {
quesTextValue = this.add.text(50,541, ques[0],textStyleQues);
this.generateQues();
//tempNoun = [];
},
generateAns: function() {
//Generate two digitd rendom no. and create an array of ans setAns[]
// Add digitd in array
for(var i = 0; i < 3 ; i++) {
var digit = Math.floor(Math.random() * 90 + 10);
//console.log(digit);
setAns.push(digit);
astroidContains[i] = "wrong";
}
console.log(astroidContains);
//console.log(answear);
setAns.push(answear[0]);
astroidContains[i] = "right";
console.log(astroidContains);
shuffle(setAns);
randomAnsPosition = [0, 1, 2, 3];
shuffle(randomAnsPosition);
},
comeAns: function() {
// x and y axis param for placing Answers text.
xAxis = [ 85, 255, 453, 675];
yAxis = [130, 48, 60, 120];
// console.log(setAns);
// Set Answers from above array of Ans - setAns.
for (var i = 0; i < setAns.length; i++) {
var ans = setAns[i];
//console.log(ans);
ansTextValue = this.add.text(xAxis[randomAnsPosition[i]], yAxis[randomAnsPosition[i]], ans, textStyleAns);
astroidContainsText[i] = ansTextValue;
//console.log(ansTextValue.text);
}
},
// Observing which cloud is clicked and checking answer accordingly.
astroidClicked: function() {
// alert("HEllo called");
if(!allowClick) {
return;
}
if(astroid1.game.input._x > 85 && astroid1.game.input._x < 130) {
console.log("cloud_1_Clicked, Clicked:" + astroidContains[0]);
this.checkAnswer(0);
}
else if(astroid2.game.input._x > 255 && astroid2.game.input._x < 48) {
//console.log("cloud_2_Clicked, Clicked:" + astroidContains[1]);
this.checkAnswer(1);
}
else if(astroid3.game.input._x > 453 && astroid3.game.input._x < 60) {
//console.log("cloud_3_Clicked, Clicked:" + astroidContains[2]);
this.checkAnswer(2);
}
else if(astroid4.game.input._x > 675 && astroid4.game.input._x < 120) {
//console.log("cloud_3_Clicked, Clicked:" + astroidContains[2]);
this.checkAnswer(3);
}
allowClick = false;
},
startTimer: function() {
// Create our Timer
timer = game.time.create(false);
// Set a TimerEvent to occur after 1 seconds
timer.loop(1000, this.updateCounter, this);
// Set a TimerEvent to occur after 1 seconds
// timer.loop(100, this.timerStripeChange, this);
// Start the timer running - this is important!
// It won't start automatically, allowing you to hook it to button events and the like.
timer.start();
},
gameOver: function() {
//Gameover screen
this.state.start('Game_Over', true, false);
},
initLoader: function() {
//*******Loader
check +=1;
var bmd = this.game.add.bitmapData(185, 30);
bmd.ctx.beginPath();
bmd.ctx.rect(0, 0, 185, 36);
bmd.ctx.fillStyle = '#00685e';
bmd.ctx.fill();
var bglife = this.game.add.sprite(100, 38, bmd);
bglife.anchor.set(0.5);
if(check != 0)
bmd = this.game.add.bitmapData(x_loader-4, 26);
else
bmd = this.game.add.bitmapData(x_loader, 26);
bmd.ctx.beginPath();
bmd.ctx.rect(0, 0, 180, 26);
if(x_loader <= 120 && x_loader > 60) {
bmd.ctx.fillStyle = "#FFFF00";
} else if(x_loader <= 60) {
bmd.ctx.fillStyle = "#EA0B1E";
} else {
bmd.ctx.fillStyle = '#00f910';
}
bmd.ctx.fill();
this.widthLife = new Phaser.Rectangle(0, 0, bmd.width, bmd.height);
this.totalLife = bmd.width;
//x_loader = ;
/*console.log(this.totalLife);
console.log(this.widthLife);*/
this.life = this.game.add.sprite(93 - bglife.width/2 + 10, 38, bmd);
this.life.anchor.y = 0.5;
this.life.cropEnabled = true;
this.life.crop(this.widthLife);
// this.game.time.events.loop(1450, this.cropLife, this);
},
updateCounter: function() {
if(timerCounter <= 0) {
this.gameOver();
return;
}
timerCounter--;
if(this.widthLife.width <= 0){
this.widthLife.width = this.totalLife;
}
else{
//this.game.add.tween(this.widthLife).to( { width: (x_loader - 4) }, 200, Phaser.Easing.Linear.None, true);
//console.log(this.widthLife.width);
this.widthLife.width = x_loader - 4;
x_loader = this.widthLife.width;
}
},
fire: function () {
if (game.time.now > nextFire && bullets.countDead() > 0)
{
nextFire = game.time.now + fireRate;
var bullet = bullets.getFirstDead();
bullet.reset(sprite.x - 80, sprite.y - 80);
game.physics.arcade.moveToPointer(bullet, 300);
}
}
}
/**
* Shuffles array in place.
* #param {Array} a items The array containing the items.
*/
function shuffle(a) {
var j, x, i;
for (i = a.length; i; i -= 1) {
j = Math.floor(Math.random() * i);
x = a[i - 1];
a[i - 1] = a[j];
a[j] = x;
}
}
As already noted it is a lot of code.
So far what I can see, is a memory leak in the update() function:
bullets = game.add.group();
bullets.enableBody = true;
bullets.physicsBodyType = Phaser.Physics.ARCADE;
bullets.createMultiple(200, 'bullet', 100, false);
bullets.setAll('anchor.x',0);
bullets.setAll('anchor.y', 0.9);
bullets.setAll('outOfBoundsKill', true);
bullets.setAll('checkWorldBounds', true);
With that you are constantly creating new bullets. Put that in the create() function and try again.

Javascript OOP : Help retrieving value from my this.obj.value [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
Enchant.js is not familiarly used, but since it using same OOP style like prototype.js i think i've got a chance to ask it here.
this is my main.js:
var DIR_LEFT = 0;
var DIR_RIGHT = 1;
var DIR_UP = 2;
var DIR_DOWN = 3;
enchant();
window.onload = function () {
game = new Core(320, 320);
game.preload(
'res/map0.png',
'res/chara0.png'
);
game.fps = 30;
game.onload = function() {
var sceneGame = new SceneGame();
game.pushScene(sceneGame);
}
game.start();
//main gameplay scene
var SceneGame = Class.create(Scene, {
initialize: function() {
Scene.apply(this);
var stage, map, player, label;
stage = new Group();
map = tileMap(game.assets['res/map0.png']);
player = new Player();
label = new Label("hi!");
player.addEventListener(Event.ENTER_FRAME, this.update);
this.player = player;
this.map = map;
stage.addChild(map);
stage.addChild(player);
this.Elx = 1;
this.label = label;
this.addChild(stage);
this.addChild(label);
var pad = new Pad();
pad.y = 220;
this.addChild(pad);
},
update: function() {
this.Elx = 2;
console.log("Elx :" + this.Elx );
console.log(this.player.x);
}
});
var Player = Class.create(Sprite, {
initialize: function() {
Sprite.apply(this, [32, 32]);
this.image = game.assets['res/chara0.png'];
this.x = 2 * 16;
this.y = 16;
this.dir = DIR_DOWN;
this.anim = [
9, 10, 11, 10,
18, 19, 20, 19,
27, 28, 29, 28,
0, 1, 2, 1];
// Frame setting
if (!game.input.up && !game.input.down && !game.input.right && !game.input.left) {
this.age = 1;
this.frame = this.anim[this.dir * 4 + (this.age % 4)];
}
},
update: function (evt) {
}
});
}
initialize is the Enchant.js object constructor method,
the code above successfully returning the stage group child ( map and player) images on screen, but when i want to use on update SceneGame's method,
the console returned 2 for the this.Elx
but returning undefined error for this.player.x .
Why this is happening ?
any help are appreciated . thank you
thank you guys for your answer, so basically is my fault for lack of understanding about the Grouping method. So in the line i declared :
map = tileMap(game.assets['res/map0.png']);
this.map = map;
player = new Player();
this.player = player;
stage = new Group();
stage.addChild(player);
stage.addChild(map);
map.addChild(stage);
and in the update i tried to call console.log(this.player)
of course it wont work because the player inserted in scene as a child. I tried to change above line to :
map = tileMap(game.assets['res/map0.png']);
player = new Player();
stage = new Group();
stage.addChild(player);
this.player = stage.childNodes[0];
stage.addChild(map);
this.map = stage.childNodes[1];
map.addChild(stage);
above code succesfully return any property of this.player.
So this is solved . thank you :)

EaselJS Sprite gotoAndPlay won't loop

I used EaselJS to animate a Sprite. I managed to make it move to the right and to the left. The point is I used gotoAndPlay to animate my sprite when moving, but my Sprite only does the animation once, then stops on the last frame. I tried to change the frequency, to activate the loop, but nothing works. I hope you can figure out where my mistake is, thank you.
Here is my code:
var stage,
img = new Image(),
bg = new Image(),
bgBitmap,
link,
text,
clavier = {
gauche: 0,
droite: 0
};
window.onkeydown = keyPress;
window.onkeyup = keyRelease;
function keyPress(e) {
var i;
if (e.keyCode == 37) {
clavier.gauche = 1;
for (i = 0; i < 10; i++) {
link.gotoAndPlay("wkLeft");
}
}
if (e.keyCode == 39) {
clavier.droite = 1;
link.gotoAndPlay("wkRight");
}
}
function keyRelease(e) {
if (e.keyCode == 37) {
clavier.gauche = 0;
link.gotoAndPlay("stand");
}
if (e.keyCode == 39) {
clavier.droite = 0;
link.gotoAndPlay("stand");
}
}
function init() {
stage = new createjs.Stage('mon_canvas');
bg.src = "img/bg.png";
bg.onload = creationBg();
img.src = "img/img.png";
img.onload = creationPerso();
createjs.Ticker.useRAF = true;
createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener("tick", stage);
createjs.Ticker.addEventListener("tick", tick);
}
function creationPerso() {
var ss = new createjs.SpriteSheet({
images: [img],
frames: {
height: 90,
width: 90,
regX: 45,
regY: 45
},
animations: {
wkRight: {
frames: [5, 9, true, 6],
speed: 0.1
},
stand: [15],
wkLeft: {
frames: [0, 4, true, 6],
speed: 0.1
}
}
});
link = new createjs.Sprite(ss, "stand");
link.x = stage.canvas.width / 2;
link.y = 280;
stage.addChild(link);
}
function tick() {
deplacement();
scene.update();
}
function creationBg() {
bgBitmap = new createjs.Bitmap(bg);
bgBitmap.regX = 400;
bgBitmap.regY = 300;
bgBitmap.x = 400;
bgBitmap.y = 100;
bgBitmap.scaleX = 1;
bgBitmap.scaleY = 1;
stage.addChild(bgBitmap);
}
function deplacement() {
if (clavier.gauche == 1) {
link.x = link.x - 1;
}
if (clavier.droite == 1) {
link.x = link.x + 1;
}
}
window.onload = init;
Your SpriteSheet format is not correct. You have used the long-form animation format, where frames should include a list of frame numbers - but you have used 5,9,true,6 -- which looks like the short form (start, end, next, speed).
Here is a fixed definition using the short form instead.
var ss = new createjs.SpriteSheet({
images: [img],
frames: {
height: 90,
width: 90,
regX: 45,
regY: 45
},
animations: {
wkRight: [5, 9, true, 0.1]
stand: [15],
wkLeft: [0, 4, true, 0.1]
}
});
Note that if your walk animations are just flipped for left/right, then you can flip the sprite using scaleX=-1, reducing the number of frames in your SpriteSheet.
Let me know if that helps. It would also help if you posted a sample, maybe on JSFiddle. Here is a SpriteSheet sample I have used: http://jsfiddle.net/lannymcnie/g5epoydb/2/

Categories

Resources