EaselJS Sprite gotoAndPlay won't loop - javascript

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/

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>

Draw line in Phaser 3

I need your help. I am newbie in Phaser 3. I want to create game with simple rules. There are 36 dots, which situated in 6 rows. Player needs to unite dots with a line, but he can only unite dots with same color and union can happen only vertically and horizontally. So, you can't draw daigonal line. When you will finish union, dots will vanish. How I can realize union with line? My current code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/phaser.min.js"></script>
</head>
<body>
<script>
let config = {
type: Phaser.AUTO,
width: 800,
height: 600,
backgroundColor: '#f0ebeb',
physics: {
default: 'arcade',
arcade: {
gravity: { y: 300 },
debug: false
}
},
scene: {
preload: preload,
create: create,
update: update
},
scale: {
autoCenter: Phaser.Scale.CENTER_BOTH
}
};
let game = new Phaser.Game(config);
let items = [];
function preload() {
for (let i = 1; i < 6; i++)
this.load.image(i, 'img/' + i + '.png');
}
function create() {
let x = 100;
let y = 0;
for (i = 0; i < 36; i++) {
if (i % 6 === 0) {
y += 85;
x = 100;
}
this.add.image(x, y, getRandomInt(5).toString())
x += 125;
}
}
function update() { }
function getRandomInt(max) {
return Math.floor(Math.random() * max) + 1;
}
</script>
</body>
</html>
I want something like this
I would just allow the user only to select (draw a line) to next valid circles.
A valid circle being, on the same row or same column or same color or max union length or ...
And when the drawing is finished I would, only allow union, when more than one circle is selected (is in the given path).
Here a short demo, how it could look like:
let config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 400,
height: 200,
banner: false,
scene: { create }
};
let game = new Phaser.Game(config);
let isDragging = false;
let lineStartPosition = {x:0 , y:0};
let currentPath = [];
let currentColor;
let line;
let pathGraphics;
function create ()
{
let cicles = []
for(let rowIdx = 0; rowIdx < 4; rowIdx++ ){
for(let colIdx = 0; colIdx < 2; colIdx++ ){
let circle = this.add.circle(50 + 100 * rowIdx, 50 + 100 * colIdx, 25, 0x6666ff).setOrigin(.5);
// Just to test a different color
if(rowIdx + colIdx ==2){
circle.fillColor = 0xff0000;
}
circle.setInteractive();
cicles.push(circle);
}
}
line = this.add.line(0,0, 0,0, 100, 100, 0xffffff).setOrigin(0);
line.setLineWidth(5);
line.visible = false;
pathGraphics = this.add.graphics();
// adding the events to the scene
this.input.on('pointerdown', dragStart);
this.input.on('pointerup', dragEnd);
this.input.on('pointermove', drag);
}
function dragStart(pointer, gameObjects){
if(gameObjects.length == 0){
return;
}
isDragging = true;
// remember Starting Color
currentColor = gameObjects[0].fillColor;
// initialize Path
currentPath = [gameObjects[0]];
// draw/save last segment of the path
lineStartPosition.x = gameObjects[0].x;
lineStartPosition.y = gameObjects[0].y;
line.x = gameObjects[0].x;
line.y = gameObjects[0].y;
line.setTo(0, 0, 0, 0);
line.visible = true;
}
function drag(pointer, gameObjects ){
if(isDragging == true){
// Check If Circle is allowed to be added, to path
// Here you would also check if the line is horizontal or vertical (this part is currently not implemented)
if(gameObjects[0] && currentPath.indexOf(gameObjects[0]) === -1 && currentColor == gameObjects[0].fillColor){
currentPath.push(gameObjects[0]);
line.x = gameObjects[0].x;
line.y = gameObjects[0].y;
lineStartPosition.x = gameObjects[0].x;
lineStartPosition.y = gameObjects[0].y;
}
line.setTo(0, 0, pointer.x - lineStartPosition.x, pointer.y - lineStartPosition.y);
drawPath();
}
}
function drawPath(){
pathGraphics.clear();
if(currentPath.length > 0){
pathGraphics.lineStyle(10, 0xffffff);
let path = new Phaser.Curves.Path(currentPath[0].x, currentPath[0].y);
for(let idx = 1; idx < currentPath.length; idx++){
let point = currentPath[idx];
path.lineTo(point.x, point.y);
}
path.draw(pathGraphics);
}
}
function dragEnd(pointer, gameObjects){
if(gameObjects.length == 0){
return;
}
if(currentPath.length < 2) {
console.info('No valid path');
return
} else {
console.info(`Valid Union path, length: ${currentPath.length}`);
}
line.visible = false;
isDragging = false;
}
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>

Phaser.js why overlap doesn't work?

I created a little scene on phaser.js
When the enemy shoots me, I have to die, but it don't work
And also, when I shoot the enemies they should die. I wrote an overlap function in code, but it doesn't work.
Here is a screenshot of the situation:
Why is this so, can you help me?
var playState = {
create: function()
{
this.enemiesArray = [];
game.physics.startSystem(Phaser.Physics.ARCADE);
this.spacebar;
this.spacebar = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
this.escapeKey = game.input.keyboard.addKey(Phaser.Keyboard.ESC);
this.ship = game.add.sprite(game.width / 2, game.height / 2 + 300, 'ship');
this.ship.anchor.setTo(0.5, 0.5);
this.ship.scale.setTo(0.4, 0.4);
this.cursor = game.input.keyboard.createCursorKeys();
this.enemy = game.add.sprite(game.width / 2, game.height / 2 - 300, 'alien');
this.enemy.anchor.setTo(.5,.5);
this.enemy.scale.setTo(0.4,0.4);
game.time.events.loop(1000, this.spawnEnemy, this);
game.time.events.loop(750, this.spawnEnemyBullet, this);
game.physics.arcade.enable(this.ship, this.enemy, this.bullet, this.enemyBullet);
},
update: function()
{
if(this.cursor.left.isDown)
{
this.ship.x -= 7;
}
for(var a = 0; a < this.enemiesArray.length; a++)
{
this.enemiesArray[a].x -= 2;
}
if(this.escapeKey.isDown)
{
game.state.start('menu');
}
if(this.cursor.right.isDown)
{
this.ship.x += 7;
}
if(this.spacebar.isDown)
{
this.bullet = game.add.sprite(this.ship.x, this.ship.y, 'bullet');
this.bullet.anchor.setTo(0.5,0.5);
this.bullet.scale.setTo(0.2,0.2);
game.physics.arcade.enable(this.bullet);
this.bullet.body.velocity.y = -600;
if(!this.bullet.inWorld)
{
this.bullet.kill();
}
}
game.physics.arcade.overlap(this.enemyBullet,this.ship,this.gameOverOpenMenuScreen,null,this);
game.physics.arcade.overlap(this.bullet,this.enemy,this.killenemy,null,this);
},
killenemy: function()
{
this.enemy.kill();
},
gameOverOpenMenuScreen: function()
{
game.state.start('menu');
},
spawnEnemy: function()
{
this.enemy = game.add.sprite(Math.random()*game.width, game.height / 2 - 300, 'alien');
this.enemy.anchor.setTo(.5,.5);
this.enemy.scale.setTo(0.4,0.4);
this.enemiesArray.push(this.enemy);
},
spawnEnemyBullet: function()
{
for(var i = 0; i < this.enemiesArray.length; i++)
{
this.enemyBullet = game.add.sprite(this.enemiesArray[i].x, this.enemiesArray[i].y, 'bullet');
this.enemyBullet.anchor.setTo(0.5,0.5);
this.enemyBullet.scale.setTo(0.2,0.2);
this.enemyBullet.angle = 180;
game.physics.arcade.enable(this.enemyBullet);
this.enemyBullet.body.velocity.y = 600;
}
}
}
You should first group all bullets to one group:
const bulletsGroup = this.add.group();
(notice that this referees to the scene)
Then add each one of you bullets to the group:
bulletsGroup.add(<your game object>);
After those 2 steps you can set your overlap function. The function gets group/object for its first 2 arguments, and a callback to be invoked when an overlap occurs:
game.physics.arcade.overlap(this.ship, bulletGroup, () => console.log('boom!'));
You can use a group to create the bullets, but I think you should correct this first:
game.physics.arcade.enable([this.ship, this.enemy]);
Add this to your code:
create : function() {
...
//After creating the sprites
this.bulletPlayerTime = 0;
this.bulletsPlayer = game.add.group();
this.bulletsPlayer.enableBody = true;
this.bulletsPlayer.physicsBodyType = Phaser.Physics.ARCADE;
for (var i = 0; i < 20; i++)
{
var b = this.bulletsPlayer.create(0, 0, 'bullet');
b.name = 'bullet' + i;
b.exists = false;
b.visible = false;
b.checkWorldBounds = true;
b.events.onOutOfBounds.add(function(bullet) { bullet.kill(); }, this);
}
...
}
update : function() {
...
if (this.spacebar.isDown) {
this.firePlayer();
}
...
}
firePlayer : function() {
if (game.time.now > this.bulletPlayerTime) {
bullet = bulletsPlayer.getFirstExists(false);
if (bullet) {
bullet.reset(this.ship.x + 6, this.ship.y - 8);
bullet.body.velocity.y = -300;
this.bulletPlayerTime = game.time.now + 300;
}
}
}
Now you must do the same functionality but this time with the enemies ...
You can see more here

Phaser // Javascript // Player is not defined

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);
}
};

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.

Categories

Resources