Unable to initialize global variable in javascript based game - javascript

I have a flappy bird based clone game and I need to make a high-score feature for it. The high score disappears in a split second 'cause the game reloads and I don't know how to set the High Score as a global variable. Here is the link if you want to view it. (Warning: Lower headphone volume)
http://www.theindependentwolf.com/game/flappyWolf.html
// Initialize Phaser, and creates a 400x490px game
var game = new Phaser.Game(400, 490, Phaser.AUTO, 'gameDiv');
// Creates a new 'main' state that will contain the game
var mainState = {
// Function called first to load all the assets
preload: function() {
// Change the background color of the game
// game.stage.backgroundColor = '#71c5cf';
//background Image
game.load.image('woods', 'woods.jpg');
// Load the bird sprite
game.load.image('bird', 'whiteWolf2.png');
// Load the pipe sprite
game.load.image('pipe', 'pipe.png');
},
// Fuction called after 'preload' to setup the game
create: function() {
// Set the physics system
game.physics.startSystem(Phaser.Physics.ARCADE);
game.add.tileSprite(0, 0, 400, 490, 'woods');
// Display the bird on the screen
this.bird = this.game.add.sprite(100, 245, 'bird');
// Add gravity to the bird to make it fall
game.physics.arcade.enable(this.bird);
this.bird.body.gravity.y = 1000;
// Call the 'jump' function when the spacekey is hit
var spaceKey = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
spaceKey.onDown.add(this.jump, this);
// Create a group of 20 pipes
this.pipes = game.add.group();
this.pipes.enableBody = true;
this.pipes.createMultiple(20, 'pipe');
// Timer that calls 'addRowOfPipes' ever 1.5 seconds
this.timer = this.game.time.events.loop(1500, this.addRowOfPipes, this);
// Add a score label on the top left of the screen
this.score = 0;
this.hiScore = 0;
this.scoreLabel = this.game.add.text(20, 20, "Score: ", { font: "30px Arial", fill: "#ffffff" });
this.labelScore = this.game.add.text(120, 20, "0", { font: "30px Arial", fill: "#ffffff" });
this.hiScoreLabel = this.game.add.text(200, 20, "Hi Score: ", { font: "30px Arial", fill: "#ffffff" });
labelHiScore = this.game.add.text(340, 20, "0", { font: "30px Arial", fill: "#ffffff" });
/*
Code for the pause menu
*/
},
// This function is called 60 times per second
update: function() {
// If the bird is out of the world (too high or too low), call the 'restartGame' function
if (this.bird.inWorld == false)
this.restartGame();
// If the bird overlap any pipes, call 'restartGame'
game.physics.arcade.overlap(this.bird, this.pipes, this.restartGame, null, this);
},
// Make the bird jump
jump: function() {
// Add a vertical velocity to the bird
this.bird.body.velocity.y = -350;
},
// Restart the game
restartGame: function() {
// Start the 'main' state, which restarts the game
if(this.score > this.hiScore ){
labelHiScore.text = this.score;
}
game.state.start('main');
},
// Add a pipe on the screen
addOnePipe: function(x, y) {
// Get the first dead pipe of our group
var pipe = this.pipes.getFirstDead();
// Set the new position of the pipe
pipe.reset(x, y);
// Add velocity to the pipe to make it move left
pipe.body.velocity.x = -200;
// Kill the pipe when it's no longer visible
pipe.checkWorldBounds = true;
pipe.outOfBoundsKill = true;
},
// Add a row of 6 pipes with a hole somewhere in the middle
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;
},
};
// Add and start the 'main' state to start the game
game.state.add('main', mainState);
// document.getElementById("#startButton").onclick(function(){
// alert("Hi");
labelHiScore = 0;
game.state.start('main');
// });

Try with following changes:
In restartGame method:
restartGame: function() {
if(this.score > localStorage.getItem("hiScore") ){
localStorage.setItem("hiScore", this.score);
this.labelHiScore.text = localStorage.getItem("hiScore");
}
game.state.start('main');
},
In "labelHiScore" varaible Declaration:
this.labelHiScore = this.game.add.text(340, 20, ("hiScore" in localStorage ? localStorage.getItem("hiScore") : "0"), { font: "30px Arial", fill: "#ffffff" });
I hope you got what is the problem, in short
In restartGame method you are trying to assign score to window scoped variable instead of functional scope.
Adding "this." will make to find variable in current object.
Also added score to local storage to preserve highscore, and when the game is reloaded picking value from local storage.

Related

Phaser 3 - How to detect if all components are sleeping?

I am new to Phaser Framework and I wanted to try making some prototype of 2D pool game from top down perspective. The problem that I have right now is detecting if all balls have stopped moving before restarting.
I use Physics.Matter and here is the source code when create so far:
this.matter.world.setBounds(0, 0, 720, 1280, 32, false, false, false, true);
this.add.image(400, 300, 'sky');
var ball = this.matter.add.image(360, 1000, 'ball');
ball.setCircle();
ball.setVelocity(-5, -20);
ball.setBounce(0.5);
for (var i = 1; i < 10; i++) {
var target = this.matter.add.image(Phaser.Math.Between(400,450), Phaser.Math.Between(400,450), 'target');
target.setCircle();
target.setVelocity(0, 0);
target.setBounce(0.7);
target.setFriction(0, 0.01);
target.setSleepEvents(true, true);
}
this.matter.world.on('sleepstart', function() {console.log('sleepstart');});
this.matter.world.on('sleepend', function() {console.log('sleepend');});
This would detect if each target has slept but I need to detect if ALL of them stopped moving. I cannot count how many has slept because sometimes when a target has entered sleep state, there is a chance some other body will bounce off it and woke it up again.
Is there any way to globally detect them?
EDIT: As a fallback plan I add a basic JS function to be called whenever update is called and count the sleeping bodies, which looks like it should not be a proper way:
var isActive = false;
// Some commands here that changes isActive = true
function onupdate() {
if (isActive) {
var bodyCount = this.matter.world.getAllBodies().filter(o => o.isSleeping === true).length;
console.log(bodyCount);
if (bodyCount >= 11) {
isActive = false;
}
}
}
I would put all objects you want to track into a phaser group (https://photonstorm.github.io/phaser3-docs/Phaser.GameObjects.Group.html) and iterate over the items in the group, to see if all have the property isSleeping set to true;
Warning: I can't say how performant this solution is, youre use case. If it is too slow, I would setup a counter variable, and count it down / up on sleepstart and sleepend. And when the counter is 0 all are sleeping.
Here a working demo, how I would do it:
(explaination are in the code, as comments)
// fix to prevent 'Warnings' in stackoverflow console
console.warn = _ => _
var config = {
type: Phaser.AUTO,
width: 400,
height: 100,
scene: { create },
physics: {
default: 'matter',
matter: {
debug: true,
setBounds: {
x: 0,
y: 0,
width: 400,
height: 100
},
enableSleeping: true
}
}
};
function create(){
// create the Phaser Group
this.targets = this.add.group();
for (var i = 1; i < 10; i++) {
var target = this.matter.add.image(200, 0, 10, 10, 'target');
target.setCircle();
target.setBounce(0.7);
target.setFriction(0, 0.01);
target.setSleepEvents(true, true);
// Add Item to the Group
this.targets.add(target);
}
this.matter.world.on('sleepstart', function(event, item){
// Check all targets are sleeping
if(!this.targets.getChildren().some( target => !target.body.isSleeping)){
console.log('all are sleeping');
}
}, this); // <- pass the scene as context
this.matter.world.on('sleepend', function() {console.log('sleepend');});
}
var game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>

How to collide a player with walls?

I'm trying to create a top down shooter game and I am using Tiled to create my map. I've made my map and exported it as a .json file. I was finally able to make the map appear in my game, but I am having a hard time making the collision work.
I've been going through tutorials for hours and seem to have tried everything under the sun with no luck. I have an object layer in Tiled with the walls marked with the insert rectangle tool. I have every wall tile also marked with insert rectangle in the edit tileset menu. But I still cant get it to work. Walls are Tile Layer 1, ground is Tile Layer 2, object layer is called collision and the tile set name is tiles 48x48. Here's all my relevant code:
var game = new Phaser.Game(1440, 960, Phaser.man, 'phaser-example', { preload: preload, create: create, update: update, render: render });
var sprite
//sounds
var music
//movement
var controls
var cursors
//shooting
var fireRate = 200;
var nextFire = 0;
var Bullets
//map
var map
var walls
var ground
//var collision
function preload() {
game.load.audio('groove', ['sewer groove.mp3']);
game.load.audio('gunshot', 'pistol.mp3');
game.load.image('player', 'player lite.png');
game.load.image('bullet', 'bullet.png');
game.load.tilemap('map', 'sewermap.json', null, Phaser.Tilemap.TILED_JSON);
game.load.image('tiles 48x48','tiles 48x48.png')
}
function create() {
map = game.add.tilemap('map');
map.addTilesetImage('tiles 48x48');
//var tileset = map.addTilesetImage('map','tiles 48x48');
//map.physics.arcade.enable(sprite, Phaser.Physics.ARCADE);
ground = map.createLayer('Tile Layer 2');
walls = map.createLayer('Tile Layer 1');
//collision = map.createLayer('Object Layer 1')
map.setCollisionBetween(0, 65, true, 'Tile Layer 1');
//sprite.body.collideWorldbounds = true;
//layer.resizeWorld();
music = game.add.audio('groove',1,true);
music.play();
game.physics.startSystem(Phaser.Physics.ARCADE);
//game.physics.startSystem(Phaser.Physics.P2JS)
game.stage.backgroundColor = '#313131';
bullets = game.add.group();
bullets.enableBody = true;
bullets.physicsBodyType = Phaser.Physics.ARCADE;
bullets.createMultiple(50, 'bullet');
bullets.setAll('checkWorldBounds', true);
bullets.setAll('outOfBoundsKill', true);
sprite = game.add.sprite(620, 920, 'player');
sprite.anchor.set(0.5, 0.5);
//game.physics.p2.enable(sprite)
game.physics.arcade.enable(sprite, Phaser.Physics.ARCADE);
sprite.body.allowRotation = true;
cursors = game.input.keyboard.createCursorKeys();
}
function update() {
game.physics.arcade.collider(sprite, walls);
//console.log(sprite.rotation);
sprite.rotation = game.physics.arcade.angleToPointer(sprite);
if (game.input.activePointer.isDown)
{
fire();
}
//sprite.body.setZeroVelocity();
if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT))
{
sprite.x -= 4;
}
else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT))
{
sprite.x += 4;
}
if (game.input.keyboard.isDown(Phaser.Keyboard.UP))
{
sprite.y -= 4;
}
else if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN))
{
sprite.y += 4;
}
}
function fire() {
if (game.time.now > nextFire && bullets.countDead() > 0)
{
nextFire = game.time.now + fireRate;
var bullet = bullets.getFirstDead();
bullet.reset(sprite.x - 8, sprite.y - 8);
game.physics.arcade.moveToPointer(bullet, 300);
}
}
function render() {
game.debug.text('Active Bullets: ' + bullets.countLiving() + ' / ' + bullets.total, 32, 32);
game.debug.spriteInfo(sprite, 32, 450);
//game.debug.spriteBounds(sprite);
//game.debug.spriteBounds(bullets);
//game.debug.body(sprite);
}
Alright, I've had the chance to take a look at this, the issue should solely lie in how you're moving the main player:
sprite.x -= 4;
Collisions only fire if the body has a velocity, the following table by samme should sum it up
You can apply acceleration, for the sake of example, to move the character towards the direction you're pointing at:
if (game.input.keyboard.isDown(Phaser.Keyboard.UP) || game.input.keyboard.isDown(Phaser.Keyboard.W)) {
game.physics.arcade.accelerationFromRotation(sprite.rotation, 200, sprite.body.acceleration);
}
In the image I'm also applying a certain drag and reducing acceleration when nothing is pressed but that's your call:
sprite.body.drag.x = 200;
sprite.body.drag.y = 200;
If you wanted to strafe an idea could be at dealing with multiple presses and applying a different accelerationFromRotation accordingly (with a variety of degrees converted with Phaser.Math.degToRad)
For debug's sake, if needed, you might want to use some of the following:
[...]
walls = map.createLayer("Tile Layer 1");
walls.debug = true;
[...]
function collisionHandler(obj1, obj2) {
console.log("Colliding!", obj1, obj2)
}
game.physics.arcade.collide(sprite, walls, collisionHandler, null, this);
game.debug.body(sprite);

How to get Phaser 3 to output final score

I'm creating my first Phaser 3 game and I need to output the final score to be used by another .js file that will output to a mysql database. I also need to be able to import the current highscore from said database into the phaser game.
final score is stores and var finalScore
database table name is highScores with the columns id, userName, score, date (date is so we can sort high scores by all time high scores, monthly high scores and daily high scores)
But I just need help getting the finalScore out of phaser and currentHighScore into phaser
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Making your first Phaser 3 Game - Part 10</title>
<script src="//cdn.jsdelivr.net/npm/phaser#3.11.0/dist/phaser.js"></script>
<style type="text/css">
body {
margin: 0;
}
</style>
</head>
<body>
<script type="text/javascript">
var config = {
type: Phaser.AUTO,
width: 800,
height: 600,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 300 },
debug: false
}
},
scene: {
preload: preload,
create: create,
update: update
}
};
var player;
var stars;
var bombs;
var platforms;
var cursors;
var score = 0;
var gameOver = false;
var scoreText;
// var userName;
var game = new Phaser.Game(config);
function preload() {
this.load.image('sky', 'assets/sky.png');
this.load.image('ground', 'assets/platform.png');
this.load.image('star', 'assets/star.png');
this.load.image('bomb', 'assets/bomb.png');
this.load.spritesheet('dude', 'assets/dude.png', { frameWidth: 32, frameHeight: 48 });
}
function create() {
// A simple background for our game
this.add.image(400, 300, 'sky');
// The platforms group contains the ground and the 2 ledges we can jump on
platforms = this.physics.add.staticGroup();
// Here we create the ground.
// Scale it to fit the width of the game (the original sprite is 400x32 in size)
platforms.create(400, 568, 'ground').setScale(2).refreshBody();
// Now let's create some ledges
platforms.create(600, 400, 'ground');
platforms.create(50, 250, 'ground');
platforms.create(750, 220, 'ground');
// The player and its settings
player = this.physics.add.sprite(100, 450, 'dude');
// Player physics properties. Give the little guy a slight bounce.
player.setBounce(0.2);
player.setCollideWorldBounds(true);
// Our player animations, turning, walking left and walking right.
this.anims.create({
key: 'left',
frames: this.anims.generateFrameNumbers('dude', { start: 0, end: 3 }),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'turn',
frames: [{ key: 'dude', frame: 4 }],
frameRate: 20
});
this.anims.create({
key: 'right',
frames: this.anims.generateFrameNumbers('dude', { start: 5, end: 8 }),
frameRate: 10,
repeat: -1
});
// Input Events
cursors = this.input.keyboard.createCursorKeys();
// Some stars to collect, 12 in total, evenly spaced 70 pixels apart along the x axis
stars = this.physics.add.group({
key: 'star',
repeat: 11,
setXY: { x: 12, y: 0, stepX: 70 }
});
stars.children.iterate(function (child) {
// Give each star a slightly different bounce
child.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8));
});
bombs = this.physics.add.group();
// The score
scoreText = this.add.text(16, 16, 'score: 0', { fontSize: '32px', fill: '#000' });
// Collide the player and the stars with the platforms
this.physics.add.collider(player, platforms);
this.physics.add.collider(stars, platforms);
this.physics.add.collider(bombs, platforms);
// Checks to see if the player overlaps with any of the stars, if he does call the collectStar function
this.physics.add.overlap(player, stars, collectStar, null, this);
this.physics.add.collider(player, bombs, hitBomb, null, this);
}
function update() {
if (gameOver) {
var timeStamp = Math.floor(Date.now()) / 1000;
// gets the userName from the player
var userName = prompt("Please enter your name", "name");
//localStorage.setItem("playerName", userName);
// Save score to final score, score will be reset to zero when game restarts
finalScore = score;
console.log("User: " + userName + "'s score is " + finalScore + " at " + timeStamp + ".");
// Reset gameOver to prevent update() loop and prepare game to restart
gameOver = false;
window.confirm("Would you like to play again?");
// add call to start function again
// if (confirm("Press a button!")) {
// this.game.state.restart()
// } else {
return;
// }
}
if (cursors.left.isDown) {
player.setVelocityX(-160);
player.anims.play('left', true);
}
else if (cursors.right.isDown) {
player.setVelocityX(160);
player.anims.play('right', true);
}
else {
player.setVelocityX(0);
player.anims.play('turn');
}
if (cursors.up.isDown && player.body.touching.down) {
player.setVelocityY(-330);
}
}
function collectStar(player, star) {
star.disableBody(true, true);
// Add and update the score
score += 10;
scoreText.setText('Score: ' + score);
if (stars.countActive(true) === 0) {
// A new batch of stars to collect
stars.children.iterate(function (child) {
child.enableBody(true, child.x, 0, true, true);
});
var x = (player.x < 400) ? Phaser.Math.Between(400, 800) : Phaser.Math.Between(0, 400);
var bomb = bombs.create(x, 16, 'bomb');
bomb.setBounce(1);
bomb.setCollideWorldBounds(true);
bomb.setVelocity(Phaser.Math.Between(-200, 200), 20);
bomb.allowGravity = false;
}
}
function hitBomb(player, bomb) {
this.physics.pause();
player.setTint(0xff0000);
player.anims.play('turn');
gameOver = true;
}
// Function to post data to database
// need to get api input format from Zack
module.exports = {
userName: userName,
score: finalScore,
last_date: timeStamp
};
</script>
</body>
</html>
Use Ajax to send the high score to a specific page and then you can use $_POST in PHP to put it in your database. You can use PHP to save the date, time, score, username, etc. Ensure the game name is unique & use that for PHP to reference which index in the database table you created for game scores.
Here is an example save function from games I help develop (for IBP Arcade or SMF Arcade):
function submitScore(score)
{
let pathArray = window.location.pathname.split('/'), newpath = '', currentPath = '';
for (i = 0; i < pathArray.length; i++) {
currentPath = pathArray[i].toString().toLowerCase();
if (currentPath == 'arcade' || currentPath == 'games')
break;
newpath += '/' + pathArray[i];
}
scorepost(window.location.protocol + '//' + window.location.hostname.replace(/[/]+$/, '') + '/' + newpath.replace(/^[/]+/, '') + '/index.php?act=Arcade&do=newscore', {
gname : 'html5_game_name',
gscore: score
});
}
You'll likely have to edit how it determines the URL a bit. The above function was made for 2 different Arcade's and is designed to work for websites contained in either parent or sub-paths.
Call that function right where you have it using the console log.
To get the high scores from your database to be accessible in your game you can use PHP to create an API page with the basic sought data. Use javascript to call the page with the game name as a reference & then use DOM to gather the data. The HTML on the API page can be contained in a parent pre tag. You can use DOM to access its children that has the data like date, score, user name, etc.

Sprites not loading on canvas

I'm trying to create a game with sprite animation, but I can't seem to load both the animated sprite and the canvas at the same time. When the canvas loads, there is no error in the console but I can't see the sprite on the canvas. When I change the code around a bit (e.g. call "Sprites()" in the render function), the animated sprite shows up but the rest of the canvas is blank.
Here are the areas of code that I believe the errors are in:
app.js
/*
Sonic class creates the player's character, Sonic the Hedgehog
Parameters -
x and y are the player's initial coordinates
sprites passes in a sprite object to add animation
speed is the pace of the game based on level
*/
var Sonic = function(x, y) {
// set initial sprite/image
this.sprite = Sprites;
this.x = x;
this.y = y;
// set initial score to 0
this.score = 0;
// set initial life count to 3
this.lives = 3;
// initialize sonic as alive
this.alive === false;
};
/*
Update sonic's sprite to give the appearance of movement
Parameter - dt, the time delta between loops
*/
Sonic.prototype.update = function(dt) {
// Sprites();
};
/*
Draw the player character on the screen in canvas' context
*/
Sonic.prototype.render = function() {
// ctx.drawImage(Resources.get(this.sprite), 30, 250);
};
// create new instance of sonic
var sonic = new Sonic(30, 250);
sprites.js
var Sprites = (function(global) {
var sonicSprite,
soniceSpriteImg;
// update and render sprite at same speed as browser redraws
function gameLoop() {
window.requestAnimationFrame(gameLoop);
ctx.clearRect(0, 0, 760, 608);
sonicSprite.update();
sonicSprite.render();
}
function sprite(options) {
var obj = {},
// current frame
frameIndex = 0,
// number of updates since current frame was displayed
tickCount = 0,
// number of updates until next frame should be displayed
ticksPerFrame = options.ticksPerFrame || 0;
// number of frames in sprite sheet
numberOfFrames = options.numberOfFrames || 1;
obj.context = options.context;
obj.width = options.width;
obj.height = options.height;
obj.image = options.image;
obj.update = function() {
tickCount += 1;
// reset tickCount once it is surpasses ticks per frame
if (tickCount > ticksPerFrame) {
tickCount = 0;
// increase frameIndex if it is less than number of frames
if (frameIndex < numberOfFrames - 1) {
// go to next frame
frameIndex += 1;
} else {
// reset frameIndex to loop if out of frames
frameIndex = 0;
}
}
};
obj.render = function() {
// clear the canvas
// obj.context.clearRect(0, 0, obj.width, obj.height);
// draw animation
obj.context.drawImage(
obj.image,
frameIndex * obj.width / numberOfFrames,
0,
obj.width / numberOfFrames,
obj.height,
0,
0,
obj.width / numberOfFrames,
obj.height);
};
// obj.render();
return obj;
}
sonicSpriteImg = new Image();
sonicSprite = sprite({
context: ctx,
width: 408.8,
height: 117,
image: sonicSpriteImg,
numberOfFrames: 4,
ticksPerFrame: 3
});
// start game loop as soon as sprite sheet is loaded
sonicSpriteImg.addEventListener("load", gameLoop);
sonicSpriteImg.src = "images/sonicrunningsheet.png";
}());
The full source code for this project is here (please excuse the messy parts, this is still in progress) https://github.com/alexxisroxxanne/sonicvszombies
The live page for it is here: http://alexxisroxxanne.github.io/sonicvszombies/
Any help would be greatly appreciated! Thanks!
In the Sonic constructor you assign this.sprite to the result of the Sprites IIFE.
var Sonic = function(x, y) {
// set initial sprite/image
this.sprite = Sprites;
...
The Sprites IIFE doesn't return anything, so Sprites is always undefined.
I guess you want to return the sonicSpriteImg there.
...
sonicSpriteImg = new Image();
sonicSprite = sprite({
context: ctx,
width: 408.8,
height: 117,
image: sonicSpriteImg,
numberOfFrames: 4,
ticksPerFrame: 3
});
// start game loop as soon as sprite sheet is loaded
sonicSpriteImg.addEventListener("load", gameLoop);
sonicSpriteImg.src = "images/sonicrunningsheet.png";
return sonicSpriteImg;
}());
In the Sonic render function you get the sprite from the resources. The resources only returns undefined there. The reason is because this.sprite isn't an img url like on the other objects (Zombie, Nyancat etc.), but an img object. So you don't have to get it from resources.
Sonic.prototype.render = function() {
// ctx.drawImage(Resources.get(this.sprite), 30, 250);
ctx.drawImage(this.sprite, 30, 250);
};
My issue was fixed when I moved the variables sonicSprite and sonicSpriteImg outside of the Sprites function and into the global context, and then, in app.js, calling sonicSprite.update(); in Sonic.prototype.update() and calling sonicSprite.render(); in Sonic.prototype.render()

Prototype animation in Kinetic JS

I would like to make a "prototype" of animations for a future game. But I'm totally a noob in kineticJS.
I have an object where I make all my functions:
var app = {}
I have a function init to build a layer, a stage and declare that I will use requestAnimationFrame:
init: function(){
layer = new Kinetic.Layer();
DrawingTab = [];
stage = new Kinetic.Stage({
container: 'canvasDemo',
width: 800,
height: 600
});
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function(callback){
window.setTimeout(callback, 1000 / 60);
};
})();
}
Secondly, I've got one function to build my rects:
createObject: function(){
rect = new Kinetic.Rect({
x: 50,
y: 50,
width: 150,
height: 150,
fill: 'black',
name: 'batteur',
id: 'batteur'
});
rect1 = new Kinetic.Rect({
x: 300,
y: 50,
width: 150,
height: 150,
fill: 'black',
name: 'batteur1',
id: 'batteur1'
});
rect2 = new Kinetic.Rect({
x: 550,
y: 50,
width: 150,
height: 150,
fill: 'black',
name: 'batteur2',
id: 'batteur2'
});
layer.add(rect);
layer.add(rect1);
layer.add(rect2);
stage.add(layer);
DrawingTab.push(rect,rect1,rect2,rect3,rect4,rect5);
}
That's all I did. And then, I want to know how to animate like that:
every 20 secondes, one of the rect (select randomly) change of color,
and the user have to click on it.
the user have 5sec to click on it, and if he doesn't click, the rect change to the beginning color.
I hope explanations are clear and something will can help me, because I'm totally lost.
You should use Kinetic.Animation for animations because it optimizes redraws. Here's an example
If your game is using sprites, you should be using the Sprite shape. Here's an example of that
You don't need requestAnimationFrame or Kinetic.Animation to handle this, considering the kind of animation you want. Only use animations if you need to change the animation status every frame.
See this working DEMO.
Using setInterval and setTimeout the application became more performant.
I reduce the time of change of color to 5 seconds and the time to click to 2 seconds, just to quickly visualization of the features.
Here is the code added:
// times (make changes according)
var timeToChange = 5000; // 5 seconds
var timeToClick = 2000; // 2 seconds
// render all rects
layer.drawScene();
// add a logical rect for each rect in DrawingTab
var LogicalTab = [];
for (var i = 0; i < DrawingTab.length; ++i) {
LogicalTab.push({
isPressed: false,
frame: 0
});
}
// return a random integer between (min, max)
function random(min, max) {
return Math.round(Math.random() * (max - min) + min);
};
// define colors
var colors = ["red", "green", "blue"];
// reset state of current rect
function reset(n) {
var drect = DrawingTab[n];
var lrect = LogicalTab[n];
// check if current rect was clicked
setTimeout(function () {
if (!lrect.isPressed) {
drect.setFill("black");
// redraw scene
layer.drawScene();
lrect.frame = 0;
}
// turn off click event
drect.off("click");
}, timeToClick);
}
// start the animation
var start = setInterval(function () {
// select a rect randomly
var rand = random(0, 2);
var drect = DrawingTab[rand];
var lrect = LogicalTab[rand];
// change color
drect.setFill(colors[lrect.frame]);
// redraw scene
layer.drawScene();
// flag that current rect is not clicked
lrect.isPressed = false;
// check for click events
drect.on("click", function () {
// flag that current rect is clicked
lrect.isPressed = true;
// hold current color
lrect.frame++;
lrect.frame = lrect.frame % colors.length;
});
// reset current rect (only if it is not clicked)
reset(rand);
}, timeToChange);
I'm a newbye here, but I hope I'm able to help. KineticJS don't need requestAnimationFrame, because it has already something that handles animations. so first of all I think you should have a look to this page
if you want to make the rect's color change every 20 s, you may do something like this:
var anim = new Kinetic.Animation(function(frame) {
if(frame.time > 20000)
{
frame.time = 0;
colors = ['red', 'blue', 'violet'];
ora = colors[Math.floor(Math.random()*3)];
DrawingTab[Math.floor(Math.random*6)].setAttrs({fill: ora});
}
},layer);
then, for the 5sec stuff, I tried to write something
var currentRect = { value:0, hasClicked : true };
var anim2 = new Kinetic.Animation(function(frame) {
if(frame.time > 20000)
{
frame.time = 0;
colors = ['red', 'lightblue', 'violet'];
ora = colors[Math.floor(Math.random()*3)];
currentRect.hasClicked = false;
currentRect.value=Math.floor(Math.random()*6);
DrawingTab[currentRect.value].setAttrs({fill: ora});
}
if (!currentRect.hasClicked && frame.time>5000)
{
DrawingTab[currentRect.value].setAttrs({fill: 'black'});
currentRect.hasClicked = true;
}
DrawingTab[currentRect.value].on('click',function(){ if (frame.time<=5000) currentRect.hasClicked = true;});
},layer);
anim2.start();
I've just tried something similiar and it looks like it's working :)
p.s. sorry about my english, I'm only a poor italian student
p.p.s. I'm sure the code can be optimized, but for now I think it can be alright

Categories