So I'm using the Phaser framework to create a space invaders game but I have a problem with and array of game objects. The array enemies is normal and I can do console.log(enemies.length) fine inside the create method but it says that enemies is not defined when I run it.
var game = new Phaser.Game(800, 600);
var bgTile;
var speed = 200;
var dropCnt = 100;
var box = function(options) {
var bmd = game.add.bitmapData(options.length, options.width);
bmd.ctx.beginPath();
bmd.ctx.rect(0, 0, options.length, options.width);
bmd.ctx.fillStyle = options.color;
bmd.ctx.fill();
return bmd;
};
var mainState = {
preload: function(){
//var music;
//game.load.audio('sound1',['track01.mp3','track01.ogg']); // need to make this spce music
game.load.image('bgTile', 'bgtile.jpg');
},
create: function(){
lives = 3;
//music = game.add.audio('sound1');
//music.loopFull(1);
this.cursor = game.input.keyboard.createCursorKeys();
game.physics.startSystem(Phaser.Physics.ARCADE);
game.world.enableBody = true;
BGTile = starfield = game.add.tileSprite(0, 0, 800, 600, 'bgTile');
game.physics.startSystem(Phaser.Physics.ARCADE);
this.player = game.add.sprite(384, 550, box({
length: 32,
width: 32,
color: '#FFFFFF'
}));
this.enemy = game.add.group();
this.enemy.enableBody = true;
var enemies= [];
for(var i = 0; i < 8; i++){
for(var j = 0; j < 8; j++){
enemies.push(this.enemy.create(i*75+100,j*30+20, box({
length: 32,
width: 16,
color: '#FF0000'
})));
}
}
var bullets= [];
this.bullet = game.add.group();
this.bullet.enableBody = true;
this.player.body.immovable = true;
this.enemy.body.immovable = true;
},
update: function(){
console.log(enemies.length);
starfield.tilePosition.y += 2;
this.player.body.velocity.y = 0;
this.player.body.velocity.x = 0;
if (this.cursor.left.isDown) {
this.player.body.velocity.x -= speed;
} else if (this.cursor.right.isDown) {
this.player.body.velocity.x += speed;
}
dropCnt--;
if(dropCnt === 0){
dropCnt = 100;
for(var i = 0; i < enemies.length;i++){
this.enemies.body.x -= 8;
console.log("test");
}
}
}
};
game.state.add('main', mainState);
game.state.start('main');
Here DEMO
enemies array is defined inside mainState.create() so therefore it's not accessible to another function inside object mainState
In order to access you have to define enemies array as object member
var mainState = {
enemies:[],
....
...
}
So now to access enemies you have to do
mainState.enemies.push(....)
mainState.enemies.pop()
Related
I am erasing the canvas drawing 1 time then Undo works fine, but when I erase more than 1 time then the Undo work as a line stroke, it works for the last step to erase but other are working as line stroke please see below code:
function Sketchpad(config) {
// Enforces the context for all functions
for (var key in this.constructor.prototype) {
this[key] = this[key].bind(this);
}
// Warn the user if no DOM element was selected
if (!config.hasOwnProperty('element')) {
console.error('SKETCHPAD ERROR: No element selected');
return;
}
this.element = config.element;
// Width can be defined on the HTML or programatically
this._width = config.width || $(this.element).attr('data-width') || 0;
this._height = config.height || $(this.element).attr('data-height') || 0;
// Pen attributes
this.color = config.color || $(this.element).attr('data-color') || '#000000';
this.penSize = config.penSize || $(this.element).attr('data-penSize') || 5;
// ReadOnly sketchpads may not be modified
this.readOnly = config.readOnly ||
$(this.element).attr('data-readOnly') ||
false;
if (!this.readOnly) {
$(this.element).css({cursor: 'crosshair'});
}
// Stroke control variables
this.strokes = config.strokes || [];
console.log(this.strokes)
this._currentStroke = {
color: null,
size: null,
lines: [],
};
// Undo History
this.undoHistory = (!bErasing) ? (config.undoHistory || []) : [];
// Animation function calls
this.animateIds = [];
// Set sketching state
this._sketching = false;
// Setup canvas sketching listeners
this.reset();
}
//
// Private API
//
Sketchpad.prototype._cursorPosition = function(event) {
return {
x: event.pageX - $(this.canvas).offset().left,
y: event.pageY - $(this.canvas).offset().top,
};
};
Sketchpad.prototype._draw = function(start, end, color, size) {
this._stroke(start, end, color, size, 'source-over');
};
Sketchpad.prototype._erase = function(start, end, color, size) {
this._stroke(start, end, color, size, 'destination-out');
};
Sketchpad.prototype._stroke = function(start, end, color, size) {
this.context.save();
if(bErasing){
this.context.globalCompositeOperation = "destination-out";
}else{
this.context.globalCompositeOperation = "source-over";
}
// if(size === 7 || size === 13){
// console.log(size)
// this.context.lineJoin = 'square';
// this.context.lineCap = 'square';
// }
// else{
this.context.lineJoin = 'round';
this.context.lineCap = 'round';
// }
this.context.strokeStyle = color;
this.context.lineWidth = size;
// switch(size){
// case 2:
// this.context.globalAlpha = 1;
// break;
// case 7:
// this.context.globalAlpha = 0.7;
// break;
// case 13:
// this.context.globalAlpha = 0.4;
// break;
// default:
// this.context.globalAlpha = 0.2;
// }
this.context.beginPath();
this.context.moveTo(start.x, start.y);
this.context.lineTo(end.x, end.y);
this.context.closePath();
this.context.stroke();
this.context.restore();
};
//
// Callback Handlers
//
Sketchpad.prototype._mouseDown = function(event) {
this._lastPosition = this._cursorPosition(event);
this._currentStroke.color = this.color;
this._currentStroke.size = this.penSize;
this._currentStroke.lines = [];
// console.log(this._currentStroke.lines)
this._sketching = true;
this.canvas.addEventListener('mousemove', this._mouseMove);
};
Sketchpad.prototype._mouseUp = function(event) {
if (this._sketching) {
this.strokes.push($.extend(true, {}, this._currentStroke));
this._sketching = false;
}
this.canvas.removeEventListener('mousemove', this._mouseMove);
};
Sketchpad.prototype._mouseMove = function(event) {
var currentPosition = this._cursorPosition(event);
this._draw(this._lastPosition, currentPosition, this.color, this.penSize);
this._currentStroke.lines.push({
start: $.extend(true, {}, this._lastPosition),
end: $.extend(true, {}, currentPosition),
});
this._lastPosition = currentPosition;
};
Sketchpad.prototype._touchStart = function(event) {
event.preventDefault();
if (this._sketching) {
return;
}
this._lastPosition = this._cursorPosition(event.changedTouches[0]);
this._currentStroke.color = this.color;
this._currentStroke.size = this.penSize;
this._currentStroke.lines = [];
this._sketching = true;
this.canvas.addEventListener('touchmove', this._touchMove, false);
};
Sketchpad.prototype._touchEnd = function(event) {
event.preventDefault();
if (this._sketching) {
this.strokes.push($.extend(true, {}, this._currentStroke));
this._sketching = false;
}
this.canvas.removeEventListener('touchmove', this._touchMove);
};
Sketchpad.prototype._touchCancel = function(event) {
event.preventDefault();
if (this._sketching) {
this.strokes.push($.extend(true, {}, this._currentStroke));
this._sketching = false;
}
this.canvas.removeEventListener('touchmove', this._touchMove);
};
Sketchpad.prototype._touchLeave = function(event) {
event.preventDefault();
if (this._sketching) {
this.strokes.push($.extend(true, {}, this._currentStroke));
this._sketching = false;
}
this.canvas.removeEventListener('touchmove', this._touchMove);
};
Sketchpad.prototype._touchMove = function(event) {
event.preventDefault();
var currentPosition = this._cursorPosition(event.changedTouches[0]);
this._draw(this._lastPosition, currentPosition, this.color, this.penSize);
this._currentStroke.lines.push({
start: $.extend(true, {}, this._lastPosition),
end: $.extend(true, {}, currentPosition),
});
this._lastPosition = currentPosition;
};
//
// Public API
//
Sketchpad.prototype.reset = function() {
// Set attributes
this.canvas = $(this.element)[0];
this.canvas.width = this._width;
this.canvas.height = this._height;
this.context = this.canvas.getContext('2d');
// Setup event listeners
this.redraw(this.strokes);
if (this.readOnly) {
return;
}
// Mouse
this.canvas.addEventListener('mousedown', this._mouseDown);
this.canvas.addEventListener('mouseout', this._mouseUp);
this.canvas.addEventListener('mouseup', this._mouseUp);
// Touch
this.canvas.addEventListener('touchstart', this._touchStart);
this.canvas.addEventListener('touchend', this._touchEnd);
this.canvas.addEventListener('touchcancel', this._touchCancel);
this.canvas.addEventListener('touchleave', this._touchLeave);
};
Sketchpad.prototype.drawStroke = function(stroke) {
for (var j = 0; j < stroke.lines.length; j++) {
var line = stroke.lines[j];
this._draw(line.start, line.end, stroke.color, stroke.size);
}
};
Sketchpad.prototype.erase = function() {
// this._erase(line.start, line.end, stroke.color, stroke.size);
};
Sketchpad.prototype.redraw = function(strokes) {
for (var i = 0; i < strokes.length; i++) {
this.drawStroke(strokes[i]);
}
};
Sketchpad.prototype.toObject = function() {
return {
width: this.canvas.width,
height: this.canvas.height,
strokes: this.strokes,
undoHistory: this.undoHistory,
};
};
Sketchpad.prototype.toJSON = function() {
return JSON.stringify(this.toObject());
};
Sketchpad.prototype.animate = function(ms, loop, loopDelay) {
this.clear();
var delay = ms;
var callback = null;
for (var i = 0; i < this.strokes.length; i++) {
var stroke = this.strokes[i];
for (var j = 0; j < stroke.lines.length; j++) {
var line = stroke.lines[j];
callback = this._draw.bind(this, line.start, line.end,
stroke.color, stroke.size);
this.animateIds.push(setTimeout(callback, delay));
delay += ms;
}
}
if (loop) {
loopDelay = loopDelay || 0;
callback = this.animate.bind(this, ms, loop, loopDelay);
this.animateIds.push(setTimeout(callback, delay + loopDelay));
}
};
Sketchpad.prototype.cancelAnimation = function() {
for (var i = 0; i < this.animateIds.length; i++) {
clearTimeout(this.animateIds[i]);
}
};
Sketchpad.prototype.clear = function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
};
Sketchpad.prototype.undo = function() {
this.clear();
var stroke = this.strokes.pop();
if (stroke) {
this.undoHistory.push(stroke);
this.redraw(this.strokes);
}
};
Sketchpad.prototype.redo = function() {
var stroke = this.undoHistory.pop();
if (stroke) {
this.strokes.push(stroke);
this.drawStroke(stroke);
}
};
and also having issue while trying the change the texture of brushes according to the pen size.
eraser is working fine and undo is also working fine the only issue is while we erase more than once, then try to undo then last erase is return to real drawing, but other previous works like as the line stroke and display the drawing as per eraser mouse move in canvas.
This is my my function to call above methods:
var x = "#CB7342",
y = 2;
var bErasing = false;
var canvas, canvasWidth, canvasHeight;
var ctx;
var lastPt=null;
var pathsry = [];
var points = [];
var state;
var colour;
// past states
function ySize(size) {
y = size;
sketchpad.penSize = y;
}
var sketchpad;
function undo(){
bErasing = false;
sketchpad.undo();
if($('#erase').hasClass('active')){
bErasing = true;
}
}
function init() {
canvas = document.getElementById('sheet');
ctx = canvas.getContext('2d');
var canvasOffset = $('#sheet').offset();
var parent = canvas.parentNode;
canvas.width = parent.clientWidth;
canvas.height = parent.clientHeight;
// alert(bErasing)
sketchpad = new Sketchpad({
element: '#sheet',
width: canvas.width,
height: canvas.height,
color: null,
penSize: 2,
globalAlpha: 0.1
});
}
$(document).on('click', "#erase", function () {
bErasing = true;
});
I'm a bit new to JavaScript and have been playing around with Phaser lately. So I'm building an infinite side scroller and everything works fine except that my player won't collide with the walls. Both sprites have physics enabled and I have tried multiple solutions, none of which work. Can you please help me out?
function bloxo()
{
var game = new Phaser.Game(1200, 600, Phaser.CANVAS, 'gameStage', { preload: preload, create: create, update: update });
var prevHole = 3;
function preload() {
game.load.image('bloxoDown','../bloxo/assets/images/bloxoDown.png');
game.load.image('bloxoUp','../bloxo/assets/images/bloxoUp.png');
game.load.image('wall','../bloxo/assets/images/platform.png',400,200);
var space;
var esc;
var player;
var walls;
var score;
}
function create() {
//Canvas With a White Bacground and Physics is Created
game.stage.backgroundColor = "#ffffff";
game.physics.startSystem(Phaser.Physics.ARCADE);
//Sets the initial Score.
score = 0;
//Sets how fast the tiles move
tileSpeed = -300;
tileWidth = game.cache.getImage('wall').width;
tileHeight = game.cache.getImage('wall').height;;
//Keys for User Input are created
space = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
esc = game.input.keyboard.addKey(Phaser.Keyboard.ESC);
//Adds Bloxo to the game as a sprite.
player = game.add.sprite(200,200,'bloxoDown');
player.scale.setTo(0.6, 0.6);
game.physics.enable(player, Phaser.Physics.ARCADE);
player.body.collideWorldBounds = true;
player.body.immovable = true;
//Walls Group is created
walls = game.add.physicsGroup();
walls.createMultiple(50, 'wall');
walls.enableBody = true;
game.physics.arcade.overlap(player, walls,null,this)
game.physics.arcade.collide(player,walls,gameOver);
// Stop the following keys from propagating up to the browser
game.input.keyboard.addKeyCapture([ Phaser.Keyboard.SPACEBAR, Phaser.Keyboard.ESC,]);
//Unpausing Function
window.onkeydown = function(event)
{
if (esc.onDown && (esc.timeDown > 2000))
{
if(game.paused)
{
game.paused = !game.paused;
pauseLbl.destroy();
}
}
}
//Add an initial platform
addWall();
//Add a platform every 3 seconds
var timerWorld = game.time.events.loop(500, addWall);
}
function update() {
if (space.isDown)
{
player.body.y -=5;
bloxoUp();
}
else
{
player.body.y +=5;
bloxoDown();
}
if(esc.isDown)
{
pauseGame();
}
}
function bloxoUp()
{
player.loadTexture('bloxoUp');
}
function bloxoDown()
{
player.loadTexture('bloxoDown');
}
function pauseGame()
{
game.paused = true;
pauseLbl = game.add.text(500, 300, 'Game Paused', { font: '30px Roboto', fill: '#aaaaaa' });
}
function addTile(x,y)
{
//Get a tile that is not currently on screen
var tile = walls.getFirstDead();
//Reset it to the specified coordinates
tile.reset(x,y);
tile.body.velocity.x = tileSpeed;
tile.body.immovable = true;
//When the tile leaves the screen, kill it
tile.checkWorldBounds = true;
tile.outOfBoundsKill = true;
}
function addWall()
{
//Speed up the game to make it harder
tileSpeed -= 1;
score += 1;
//Work out how many tiles we need to fit across the whole screen
var tilesNeeded = Math.ceil(game.world.height / tileHeight);
//Add a hole randomly somewhere
do
{
var hole = Math.floor(Math.random() * (tilesNeeded - 2)) + 1;
}while((hole > (prevHole + 2)) && (hole < (prevHole - 2)) );
prevHole = hole;
//Keep creating tiles next to each other until we have an entire row
//Don't add tiles where the random hole is
for (var i = 0; i < tilesNeeded; i++){
if (i != hole && (i != hole+1 && i != hole-1) && (i != hole+2 && i != hole-2)){
addTile(game.world.width, i * tileHeight);
}
}
}
function gameOver()
{
console.log("player hit");
player.kill();
game.state.start(game.state.current);
}
}
You have just to move collide call into your update method:
game.physics.arcade.collide(player, walls, gameOver);
Take a look to the runnable snippet below(I have resized the canvas for the preview, sorry) or Fiddle:
var game = new Phaser.Game(450, 150, Phaser.CANVAS, 'gameStage', {
preload: preload,
create: create,
update: update
});
var prevHole = 3;
function preload() {
game.load.image('bloxoDown', '../bloxo/assets/images/bloxoDown.png');
game.load.image('bloxoUp', '../bloxo/assets/images/bloxoUp.png');
game.load.image('wall', '../bloxo/assets/images/platform.png', 400, 100);
var space;
var esc;
var player;
var walls;
var score;
}
function create() {
//Canvas With a White Bacground and Physics is Created
game.stage.backgroundColor = "#ffffff";
game.physics.startSystem(Phaser.Physics.ARCADE);
//Sets the initial Score.
score = 0;
//Sets how fast the tiles move
tileSpeed = -300;
tileWidth = game.cache.getImage('wall').width;
tileHeight = game.cache.getImage('wall').height;;
//Keys for User Input are created
space = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
esc = game.input.keyboard.addKey(Phaser.Keyboard.ESC);
//Adds Bloxo to the game as a sprite.
player = game.add.sprite(200, 200, 'bloxoDown');
player.scale.setTo(0.6, 0.6);
game.physics.enable(player, Phaser.Physics.ARCADE);
player.body.collideWorldBounds = true;
player.body.immovable = true;
//Walls Group is created
walls = game.add.physicsGroup();
walls.createMultiple(50, 'wall');
walls.enableBody = true;
game.physics.arcade.overlap(player, walls, null, this)
// remove your call to collide
// Stop the following keys from propagating up to the browser
game.input.keyboard.addKeyCapture([Phaser.Keyboard.SPACEBAR, Phaser.Keyboard.ESC, ]);
//Unpausing Function
window.onkeydown = function(event) {
if (esc.onDown && (esc.timeDown > 2000)) {
if (game.paused) {
game.paused = !game.paused;
pauseLbl.destroy();
}
}
}
//Add an initial platform
addWall();
//Add a platform every 3 seconds
var timerWorld = game.time.events.loop(500, addWall);
}
function update() {
if (space.isDown) {
player.body.y -= 5;
bloxoUp();
} else {
player.body.y += 5;
bloxoDown();
}
// move your collide call here
game.physics.arcade.collide(player, walls, gameOver);
if (esc.isDown) {
pauseGame();
}
}
function bloxoUp() {
player.loadTexture('bloxoUp');
}
function bloxoDown() {
player.loadTexture('bloxoDown');
}
function pauseGame() {
game.paused = true;
pauseLbl = game.add.text(500, 300, 'Game Paused', {
font: '30px Roboto',
fill: '#aaaaaa'
});
}
function addTile(x, y) {
//Get a tile that is not currently on screen
var tile = walls.getFirstDead();
//Reset it to the specified coordinates
if (tile) {
tile.reset(x, y);
tile.body.velocity.x = tileSpeed;
tile.body.immovable = true;
//When the tile leaves the screen, kill it
tile.checkWorldBounds = true;
tile.outOfBoundsKill = true;
}
}
function addWall() {
//Speed up the game to make it harder
tileSpeed -= 1;
score += 1;
//Work out how many tiles we need to fit across the whole screen
var tilesNeeded = Math.ceil(game.world.height / tileHeight);
var prevHole;
//Add a hole randomly somewhere
do {
var hole = Math.floor(Math.random() * (tilesNeeded - 2)) + 1;
} while ((hole > (prevHole + 2)) && (hole < (prevHole - 2)));
prevHole = hole;
//Keep creating tiles next to each other until we have an entire row
//Don't add tiles where the random hole is
for (var i = 0; i < tilesNeeded; i++) {
if (i != hole && (i != hole + 1 && i != hole - 1) && (i != hole + 2 && i != hole - 2)) {
addTile(game.world.width, i * tileHeight);
}
}
}
function gameOver() {
console.log("player hit");
player.kill();
game.state.start(game.state.current);
}
canvas{
border: 5px solid #333;
margin-left:25px;
margin-top:25px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/2.6.2/phaser.min.js"></script>
I tried obfuscating JS code using javascript2img. It gave me the obfuscated code. They state, "Copy this code and paste it into your js or HTML file. That's all!". But I keep getting this error.
"Uncaught SyntaxError: Unexpected identifier game.js:1"
Un-obfuscated the code works just fine.
Example: The following doesnt work obfuscated but does without obfuscation.
var game = new Phaser.Game(400, 490, Phaser.AUTO, "gameDiv");
var mainState = {
preload: function() {
if(!game.device.desktop) {
game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
game.scale.setMinMax(game.width/2, game.height/2, game.width, game.height);
}
game.scale.pageAlignHorizontally = true;
game.scale.pageAlignVertically = true;
game.stage.backgroundColor = '#71c5cf';
game.load.image('bird', 'assets/bird.png');
game.load.image('pipe', 'assets/pipe.png');
// Load the jump sound
// game.load.audio('jump', 'assets/jump.wav');
},
create: function() {
game.physics.startSystem(Phaser.Physics.ARCADE);
this.pipes = game.add.group();
this.timer = game.time.events.loop(1500, this.addRowOfPipes, this);
this.bird = game.add.sprite(100, 245, 'bird');
game.physics.arcade.enable(this.bird);
this.bird.body.gravity.y = 1000;
// New anchor position
this.bird.anchor.setTo(-0.2, 0.5);
var spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
spaceKey.onDown.add(this.jump, this);
game.input.onDown.add(this.jump, this);
this.score = 0;
this.labelScore = game.add.text(20, 20, "0", { font: "30px Arial", fill: "#ffffff" });
// Add the jump sound
this.jumpSound = game.add.audio('jump');
this.jumpSound.volume = 0.2;
},
update: function() {
if (this.bird.y < 0 || this.bird.y > game.world.height)
this.restartGame();
game.physics.arcade.overlap(this.bird, this.pipes, this.hitPipe, null, this);
// Slowly rotate the bird downward, up to a certain point.
if (this.bird.angle < 20)
this.bird.angle += 1;
},
jump: function() {
// If the bird is dead, he can't jump
if (this.bird.alive == false)
return;
this.bird.body.velocity.y = -350;
// Jump animation
game.add.tween(this.bird).to({angle: -20}, 100).start();
// Play sound
// this.jumpSound.play();
},
hitPipe: function() {
// If the bird has already hit a pipe, we have nothing to do
if (this.bird.alive == false)
return;
// Set the alive property of the bird to false
this.bird.alive = false;
// Prevent new pipes from appearing
game.time.events.remove(this.timer);
// Go through all the pipes, and stop their movement
this.pipes.forEach(function(p){
p.body.velocity.x = 0;
}, this);
},
restartGame: function() {
game.state.start('main');
},
addOnePipe: function(x, y) {
var pipe = game.add.sprite(x, y, 'pipe');
this.pipes.add(pipe);
game.physics.arcade.enable(pipe);
pipe.body.velocity.x = -200;
pipe.checkWorldBounds = true;
pipe.outOfBoundsKill = true;
},
addRowOfPipes: function() {
var hole = Math.floor(Math.random()*5)+1;
for (var i = 0; i < 8; i++)
if (i != hole && i != hole +1)
this.addOnePipe(400, i*60+10);
this.score += 1;
this.labelScore.text = this.score;
},
};
game.state.add('main', mainState);
game.state.start('main');
I have a canvas animation that has been created with createjs. The entire animation script including init() function is loaded via jquery: $.getScript() on page load.
The init() and handlecomplete() function included below is then run which attaches the animation to a html canvas element on the page.
var canvas, stage, exportRoot, audio;
var tweens = [];
function init() {
canvas = document.getElementById("canvas");
images = images||{};
if (stage) {
stage.enableDOMEvents(false);
stage.removeAllChildren();
createjs.Ticker.removeAllEventListeners()
stage.enableDOMEvents(true);
}
if (audio ) {
audio.stop();
}
removeTweens();
exportRoot = null;
audio = null;
stage = null;
var loader = new createjs.LoadQueue(false);
loader.installPlugin(createjs.Sound);
loader.addEventListener("fileload", handleFileLoad);
loader.addEventListener("complete", handleComplete);
loader.loadManifest(lib.properties.manifest);
}
function handleComplete() {
exportRoot = new lib.animation2();
stage = new createjs.Stage(canvas);
stage.addChild(exportRoot);
stage.update();
stage.canvas.width = 1280;
stage.canvas.height = 720;
resizeToFit();
stage.update();
createjs.Ticker.setFPS(lib.properties.fps);
createjs.Ticker.addEventListener("tick", stage);
createjs.Ticker.addEventListener("tick", updateTimer);
if (lib.properties.audiovolume) {
audio = createjs.Sound.play("audio", createjs.Sound.INTERRUPT_EARLY, 0, 0, -1, lib.properties.audiovolume);
}
exportRoot.gotoAndPlay(startFrame );
}
My issue is when the user makes a change, we load the script a second time using the same jquery method which returns the updated script. The init() function then executes properly and the new animation plays correctly, but our animated text (using the animateText below) does not appear on the canvas. This function is also loaded dynamically with other functions.
Checking the tween arrays, they are being created and removed as required, but they are not visible.
They are either layered behind the new animation, or not being attached to the new canvas or something else?
Simply refreshing the page will then load the new script and text properly. So clearly something in the dynamic loading of the script?
var animateText = function(localString, startX, startY, letterClip, endObject, font, color) {
var waitAmount = 0;
var offSetAmount = 20;
for(var i = 0; i < localString.length; i++){
var fl_MyInstance = new letterClip();
fl_MyInstance.localName.text = localString[i];
if(font != null){
fl_MyInstance.localName.font = font;
}
if(color != null){
fl_MyInstance.localName.color = color;
}
var localX = startX;
var localY = startY;
fl_MyInstance.x = startX + offSetAmount;
var beginX = startX + offSetAmount
offSetAmount = offSetAmount - 4
fl_MyInstance.y = startY;
fl_MyInstance.alpha = 0;
fl_MyInstance.scaleX = 0.1;
fl_MyInstance.scaleY = 0.1;
var bounds = fl_MyInstance.getBounds();
startX += bounds.width + 0;
var target = fl_MyInstance;
var tween = createjs.Tween.get(target, {
loop: false
}).wait(waitAmount)
.to({
x: localX,
y: localY,
alpha: 1,
scaleX: 1,
scaleY: 1
}, 400, createjs.Ease.circOut);
tween.waitAmount = waitAmount;
if(endObject == null){
tween.endObject = {
x: localX,
y: localY,
alpha: 0,
scaleX: 0.1,
scaleY: 0.1
}
} else {
tween.endObject = {
x: localX - endObject.x,
y: localY - endObject.y,
alpha: endObject.alpha,
scaleX: endObject.scaleX,
scaleY: endObject.scaleY
}
}
tween.targetClip = fl_MyInstance;
tween.arrayIndex = tweens.length;
tweens.push(tween);
waitAmount += 20;
stage.addChild(fl_MyInstance);
}
}
var removeTweens = function(){
for(var i = 0; i<tweens.length; i++){
if(tweens[i] != null){
var tween = tweens[i];
stage.removeChild(tween.targetClip);
tweens[tween.arrayIndex] = null;
}
}
}
var closeTweens = function(){
for(var i = 0; i<tweens.length; i++){
if(tweens[i] != null){
var tween = tweens[i];
createjs.Tween.get(tween.targetClip, {
loop: false
}).wait(tween.waitAmount).to(tween.endObject, 400, createjs.Ease.circOut).call(function(){
stage.removeChild(tween.targetClip);
tweens[tween.arrayIndex] = null;
});
}
}
}
var finalTweens = function(){
for(var i = 0; i<tweens.length; i++){
if(tweens[i] != null){
var tween = tweens[i];
createjs.Tween.get(tween.targetClip, {
loop: false
}).to(tween.endObject, 400, createjs.Ease.circOut);
}
}
}
Since the rest of the animation works perfectly using this method of dynamic loading, I don't think it is something in the loading. But there must be something missing in animateText and reloading functions that causes the issue.
If anyone has used Phaser, perhaps you can help me with my code. I am trying to create a Flappy Bird clone, and so far it is working pretty well. However, whenever I open the game the first time, the sprites of the pipes don't seem to show up. I've preloaded both the bird and the pipe sprites, and only the bird sprite loads on the first attempt. As soon as the game restarts (when the bird dies), the pipes load normally. I am using WAMP to host a local server.
Here is my code:
var game = new Phaser.Game(400, 490, Phaser.AUTO, 'game_div');
var main_state = {
preload: function() {
this.game.stage.backgroundColor = '#66CCFF';
this.game.load.image('pipe', 'assets/pipe.png');
this.game.load.image('bird', 'assets/bird.png');
this.pipes = game.add.group();
this.pipes.createMultiple(20, 'pipe');
},
add_one_pipe: function(x, y) {
var pipe = this.pipes.getFirstDead();
pipe.reset(x, y);
pipe.body.velocity.x = -200
pipe.outOfBoundsKill = true;
},
add_row_of_pipes: function() {
var hole = Math.floor(Math.random()*5) + 1;
for (var i = 0; i < 8; i++) {
if (i != hole && i != hole + 1) {
this.add_one_pipe(400, i * 60 + 10);
}
}
this.score += 1;
this.label_score.content = this.score;
},
create: function() {
this.bird = this.game.add.sprite(100, 245, 'bird');
this.bird.body.gravity.y = 1000;
var space_key = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
space_key.onDown.add(this.jump, this);
this.timer = this.game.time.events.loop(1500, this.add_row_of_pipes, this);
this.score = 0;
var style = { font: "30px Arial", fill: "#ffffff" };
this.label_score = this.game.add.text(20, 20, "0", style);
},
update: function() {
if (this.bird.inWorld == false) {
this.restart_game();
}
this.game.physics.overlap(this.bird, this.pipes, this.restart_game, null, this);
},
jump: function() {
this.bird.body.velocity.y = -350;
},
restart_game: function() {
this.game.time.events.remove(this.timer);
this.game.state.start('main');
},
};
// Add and start the 'main' state to start the game
game.state.add('main', main_state);
game.state.start('main');
As in the tutorial, try to put the creation of the group in the create function:
create: function() {
this.bird = this.game.add.sprite(100, 245, 'bird');
this.bird.body.gravity.y = 1000;
var space_key = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
space_key.onDown.add(this.jump, this);
this.pipes = game.add.group();
this.pipes.createMultiple(20, 'pipe');
this.timer = this.game.time.events.loop(1500, this.add_row_of_pipes, this);
this.score = 0;
var style = { font: "30px Arial", fill: "#ffffff" };
this.label_score = this.game.add.text(20, 20, "0", style);
},