Phaser - How to make images fit on all devices - javascript

So I have a source code that I'm learning from but I'm having trouble making images such as the background and sprites fitting on various devices.
Here is what I have so far:
var game = new Phaser.Game(800, 600, Phaser.AUTO, '');
game.state.add('play', {
preload: function() {
this.game.load.image('forest-back', 'assets/parallax_forest_pack/layers/parallax-forest-back-trees.png');
this.game.load.image('forest-lights', 'assets/parallax_forest_pack/layers/parallax-forest-lights.png');
this.game.load.image('forest-middle', 'assets/parallax_forest_pack/layers/parallax-forest-middle-trees.png');
this.game.load.image('forest-front', 'assets/parallax_forest_pack/layers/parallax-forest-front-trees.png');
this.game.load.image('aerocephal', 'assets/allacrost_enemy_sprites/aerocephal.png');
this.game.load.image('arcana_drake', 'assets/allacrost_enemy_sprites/arcana_drake.png');
this.game.load.image('aurum-drakueli', 'assets/allacrost_enemy_sprites/aurum-drakueli.png');
this.game.load.image('bat', 'assets/allacrost_enemy_sprites/bat.png');
this.game.load.image('daemarbora', 'assets/allacrost_enemy_sprites/daemarbora.png');
this.game.load.image('deceleon', 'assets/allacrost_enemy_sprites/deceleon.png');
this.game.load.image('demonic_essence', 'assets/allacrost_enemy_sprites/demonic_essence.png');
this.game.load.image('dune_crawler', 'assets/allacrost_enemy_sprites/dune_crawler.png');
this.game.load.image('green_slime', 'assets/allacrost_enemy_sprites/green_slime.png');
this.game.load.image('nagaruda', 'assets/allacrost_enemy_sprites/nagaruda.png');
this.game.load.image('rat', 'assets/allacrost_enemy_sprites/rat.png');
this.game.load.image('scorpion', 'assets/allacrost_enemy_sprites/scorpion.png');
this.game.load.image('skeleton', 'assets/allacrost_enemy_sprites/skeleton.png');
this.game.load.image('snake', 'assets/allacrost_enemy_sprites/snake.png');
this.game.load.image('spider', 'assets/allacrost_enemy_sprites/spider.png');
this.game.load.image('stygian_lizard', 'assets/allacrost_enemy_sprites/stygian_lizard.png');
this.game.load.image('gold_coin', 'assets/496_RPG_icons/I_GoldCoin.png');
this.game.load.image('dagger', 'assets/496_RPG_icons/W_Dagger002.png');
this.game.load.image('swordIcon1', 'assets/496_RPG_icons/S_Sword15.png');
// build panel for upgrades
var bmd = this.game.add.bitmapData(250, 500);
bmd.ctx.fillStyle = '#9a783d';
bmd.ctx.strokeStyle = '#35371c';
bmd.ctx.lineWidth = 12;
bmd.ctx.fillRect(0, 0, 250, 500);
bmd.ctx.strokeRect(0, 0, 250, 500);
this.game.cache.addBitmapData('upgradePanel', bmd);
var buttonImage = this.game.add.bitmapData(476, 48);
buttonImage.ctx.fillStyle = '#e6dec7';
buttonImage.ctx.strokeStyle = '#35371c';
buttonImage.ctx.lineWidth = 4;
buttonImage.ctx.fillRect(0, 0, 225, 48);
buttonImage.ctx.strokeRect(0, 0, 225, 48);
this.game.cache.addBitmapData('button', buttonImage);
// the main player
this.player = {
clickDmg: 1,
gold: 50,
dps: 0
};
// world progression
this.level = 1;
// how many monsters have we killed during this level
this.levelKills = 0;
// how many monsters are required to advance a level
this.levelKillsRequired = 10;
},
create: function() {
var state = this;
this.background = this.game.add.group();
// setup each of our background layers to take the full screen
['forest-back', 'forest-lights', 'forest-middle', 'forest-front']
.forEach(function(image) {
var bg = state.game.add.tileSprite(0, 0, state.game.world.width,
state.game.world.height, image, '', state.background);
bg.tileScale.setTo(4,4);
});
this.upgradePanel = this.game.add.image(10, 70, this.game.cache.getBitmapData('upgradePanel'));
var upgradeButtons = this.upgradePanel.addChild(this.game.add.group());
upgradeButtons.position.setTo(8, 8);
var upgradeButtonsData = [
{icon: 'dagger', name: 'Attack', level: 0, cost: 5, purchaseHandler: function(button, player) {
player.clickDmg += 1;
}},
{icon: 'swordIcon1', name: 'Auto-Attack', level: 0, cost: 25, purchaseHandler: function(button, player) {
player.dps += 5;
}}
];
var button;
upgradeButtonsData.forEach(function(buttonData, index) {
button = state.game.add.button(0, (50 * index), state.game.cache.getBitmapData('button'));
button.icon = button.addChild(state.game.add.image(6, 6, buttonData.icon));
button.text = button.addChild(state.game.add.text(42, 6, buttonData.name + ': ' + buttonData.level, {font: '16px Arial Black'}));
button.details = buttonData;
button.costText = button.addChild(state.game.add.text(42, 24, 'Cost: ' + buttonData.cost, {font: '16px Arial Black'}));
button.events.onInputDown.add(state.onUpgradeButtonClick, state);
upgradeButtons.addChild(button);
});
var monsterData = [
{name: 'Aerocephal', image: 'aerocephal', maxHealth: 10},
{name: 'Arcana Drake', image: 'arcana_drake', maxHealth: 20},
{name: 'Aurum Drakueli', image: 'aurum-drakueli', maxHealth: 30},
{name: 'Bat', image: 'bat', maxHealth: 5},
{name: 'Daemarbora', image: 'daemarbora', maxHealth: 10},
{name: 'Deceleon', image: 'deceleon', maxHealth: 10},
{name: 'Demonic Essence', image: 'demonic_essence', maxHealth: 15},
{name: 'Dune Crawler', image: 'dune_crawler', maxHealth: 8},
{name: 'Green Slime', image: 'green_slime', maxHealth: 3},
{name: 'Nagaruda', image: 'nagaruda', maxHealth: 13},
{name: 'Rat', image: 'rat', maxHealth: 2},
{name: 'Scorpion', image: 'scorpion', maxHealth: 2},
{name: 'Skeleton', image: 'skeleton', maxHealth: 6},
{name: 'Snake', image: 'snake', maxHealth: 4},
{name: 'Spider', image: 'spider', maxHealth: 4},
{name: 'Stygian Lizard', image: 'stygian_lizard', maxHealth: 20}
];
this.monsters = this.game.add.group();
var monster;
monsterData.forEach(function(data) {
// create a sprite for them off screen
monster = state.monsters.create(1000, state.game.world.centerY, data.image);
// use the built in health component
monster.health = monster.maxHealth = data.maxHealth;
// center anchor
monster.anchor.setTo(0.5, 1);
// reference to the database
monster.details = data;
//enable input so we can click it!
monster.inputEnabled = true;
monster.events.onInputDown.add(state.onClickMonster, state);
// hook into health and lifecycle events
monster.events.onKilled.add(state.onKilledMonster, state);
monster.events.onRevived.add(state.onRevivedMonster, state);
});
// display the monster front and center
this.currentMonster = this.monsters.getRandom();
this.currentMonster.position.set(this.game.world.centerX + 100, this.game.world.centerY + 50);
this.monsterInfoUI = this.game.add.group();
this.monsterInfoUI.position.setTo(this.currentMonster.x - 220, this.currentMonster.y + 120);
this.monsterNameText = this.monsterInfoUI.addChild(this.game.add.text(0, 0, this.currentMonster.details.name, {
font: '48px Arial Black',
fill: '#fff',
strokeThickness: 4
}));
this.monsterHealthText = this.monsterInfoUI.addChild(this.game.add.text(0, 80, this.currentMonster.health + ' HP', {
font: '32px Arial Black',
fill: '#ff0000',
strokeThickness: 4
}));
this.dmgTextPool = this.add.group();
var dmgText;
for (var d=0; d<50; d++) {
dmgText = this.add.text(0, 0, '1', {
font: '64px Arial Black',
fill: '#fff',
strokeThickness: 4
});
// start out not existing, so we don't draw it yet
dmgText.exists = false;
dmgText.tween = game.add.tween(dmgText)
.to({
alpha: 0,
y: 100,
x: this.game.rnd.integerInRange(100, 700)
}, 1000, Phaser.Easing.Cubic.Out);
dmgText.tween.onComplete.add(function(text, tween) {
text.kill();
});
this.dmgTextPool.add(dmgText);
}
// create a pool of gold coins
this.coins = this.add.group();
this.coins.createMultiple(50, 'gold_coin', '', false);
this.coins.setAll('inputEnabled', true);
this.coins.setAll('goldValue', 1);
this.coins.callAll('events.onInputDown.add', 'events.onInputDown', this.onClickCoin, this);
this.playerGoldText = this.add.text(30, 30, 'Gold: ' + this.player.gold, {
font: '24px Arial Black',
fill: '#fff',
strokeThickness: 4
});
// 100ms 10x a second
this.dpsTimer = this.game.time.events.loop(100, this.onDPS, this);
// setup the world progression display
this.levelUI = this.game.add.group();
this.levelUI.position.setTo(this.game.world.centerX, 30);
this.levelText = this.levelUI.addChild(this.game.add.text(0, 0, 'Level: ' + this.level, {
font: '24px Arial Black',
fill: '#fff',
strokeThickness: 4
}));
this.levelKillsText = this.levelUI.addChild(this.game.add.text(0, 30, 'Kills: ' + this.levelKills + '/' + this.levelKillsRequired, {
font: '24px Arial Black',
fill: '#fff',
strokeThickness: 4
}));
},
onDPS: function() {
if (this.player.dps > 0) {
if (this.currentMonster && this.currentMonster.alive) {
var dmg = this.player.dps / 10;
this.currentMonster.damage(dmg);
// update the health text
this.monsterHealthText.text = this.currentMonster.alive ? Math.round(this.currentMonster.health) + ' HP' : 'DEAD';
}
}
},
onUpgradeButtonClick: function(button, pointer) {
// make this a function so that it updates after we buy
function getAdjustedCost() {
return Math.ceil(button.details.cost + (button.details.level * 1.46));
}
if (this.player.gold - getAdjustedCost() >= 0) {
this.player.gold -= getAdjustedCost();
this.playerGoldText.text = 'Gold: ' + this.player.gold;
button.details.level++;
button.text.text = button.details.name + ': ' + button.details.level;
button.costText.text = 'Cost: ' + getAdjustedCost();
button.details.purchaseHandler.call(this, button, this.player);
}
},
onClickCoin: function(coin) {
if (!coin.alive) {
return;
}
// give the player gold
this.player.gold += coin.goldValue;
// update UI
this.playerGoldText.text = 'Gold: ' + this.player.gold;
// remove the coin
coin.kill();
},
onKilledMonster: function(monster) {
// move the monster off screen again
monster.position.set(1000, this.game.world.centerY);
var coin;
// spawn a coin on the ground
coin = this.coins.getFirstExists(false);
coin.reset(this.game.world.centerX + this.game.rnd.integerInRange(-100, 100), this.game.world.centerY);
coin.goldValue = Math.round(this.level * 1.33);
this.game.time.events.add(Phaser.Timer.SECOND * 3, this.onClickCoin, this, coin);
this.levelKills++;
if (this.levelKills >= this.levelKillsRequired) {
this.level++;
this.levelKills = 0;
}
this.levelText.text = 'Level: ' + this.level;
this.levelKillsText.text = 'Kills: ' + this.levelKills + '/' + this.levelKillsRequired;
// pick a new monster
this.currentMonster = this.monsters.getRandom();
// upgrade the monster based on level
this.currentMonster.maxHealth = Math.ceil(this.currentMonster.details.maxHealth + ((this.level - 1) * 10.6));
// make sure they are fully healed
this.currentMonster.revive(this.currentMonster.maxHealth);
},
onRevivedMonster: function(monster) {
monster.position.set(this.game.world.centerX + 100, this.game.world.centerY + 50);
// update the text display
this.monsterNameText.text = monster.details.name;
this.monsterHealthText.text = monster.health + 'HP';
},
onClickMonster: function(monster, pointer) {
// apply click damage to monster
this.currentMonster.damage(this.player.clickDmg);
// grab a damage text from the pool to display what happened
var dmgText = this.dmgTextPool.getFirstExists(false);
if (dmgText) {
dmgText.text = this.player.clickDmg;
dmgText.reset(pointer.positionDown.x, pointer.positionDown.y);
dmgText.alpha = 1;
dmgText.tween.start();
}
// update the health text
this.monsterHealthText.text = this.currentMonster.alive ? this.currentMonster.health + ' HP' : 'DEAD';
}
});
game.state.start('play');

In your init or preload function, you should choose your scale mode. Please check the documentation to understand the different options:
//Options here are: NO_SCALE, EXACT_FIT, SHOW_ALL, RESIZE and USER_SCALE
this.scale.scaleMode = Phaser.ScaleManager.EXACT_FIT;
Please also check if you want to set pageAlignHorizontally and pageAlignVertically to true:
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = true;
In some cases, you will want to call the refresh method:
this.scale.refresh();

Related

Node.js Canvas image overlapping issue / canvas is creating image on top of previous image

I'm having an issue with Canvas when trying to create a generated collection of .png images.
I can create the .png files fine but the first image or the image before is not being cleared.
index.js
const fs = require("fs");
const { createCanvas, loadImage } = require("canvas");
const canvas = createCanvas(1000,1000);
const ctx = canvas.getContext("2d");
const edition = 10;
const {layers,width,height} = require("./input/config.js");
const saveLayer = (_canvas, _edition) => {
fs.writeFileSync(`./output/${_edition}.png`, _canvas.toBuffer("image/png"));
};
const drawLayer = async (_layer, _edition) => {
let element = _layer.elements[Math.floor(Math.random() * _layer.elements.length)];
const image = await loadImage(`${_layer.location}${element.fileName}`);
ctx.drawImage(
image,
_layer.position.x,
_layer.position.y,
_layer.size.width,
_layer.size.height
);
console.log(`I created the ${_layer.name} layer, and chose element ${element.name}`);
saveLayer(canvas, _edition);
};
for(let i = 0; i <= edition; i++){
layers.forEach(layer => {
drawLayer(layer, i);
});
console.log("Creating edition " + i);
};
config.js
const fs = require("fs");
const width = 1000;
const height = 1000;
const dir = __dirname;
const rarity = [
{key: "", val: "original" },
{key: "_r", val: "rare" },
{key: "_sr", val: "super rare" },
];
const addRarity = (_str) => {
let itemRarity;
rarity.forEach((r) => {
if (_str.includes(r.key)){
itemRarity = r.val;
}
});
return itemRarity;
};
const cleanName = (_str) => {
let name = _str.slice(0, -4);
return name;
};
const getElements = (path) => {
return fs
.readdirSync(path)
//.filter((item) => !/(^|\/)\.|^\/\.|/g.test(item))
.map((i,index) => {
return {
id: index,
name: cleanName(i),
fileName: i,
rarity: addRarity(i),
};
});
};
const layers = [
{
id: 1,
name: "0",
location: `${dir}/0/`,
elements: getElements(`${dir}/0/`),
position: {x:0, y:0},
size: {width: width, height: height},
},
{
id: 2,
name: "1",
location: `${dir}/1/`,
elements: getElements(`${dir}/1/`),
position: {x:0, y:0},
size: {width: width, height: height},
},
{
id: 3,
name: "2",
location: `${dir}/2/`,
elements: getElements(`${dir}/2/`),
position: {x:0, y:0},
size: {width: width, height: height},
},
{
id: 4,
name: "3",
location: `${dir}/3/`,
elements: getElements(`${dir}/3/`),
position: {x:0, y:0},
size: {width: width, height: height},
},
{
id: 5,
name: "4",
location: `${dir}/4/`,
elements: getElements(`${dir}/4/`),
position: {x:0, y:0},
size: {width: width, height: height},
},
];
//console.log(layers);
module.exports = {layers,width,height};
The code is working fine and I'm able to create 10 .png files.
From the images above you can see the blue hat from Image 1 is still showing in Image 2.
Edit: What I've tried -
ctx.beginPath();
context.clearRect(0, 0, canvas.width, canvas.height);
const createNFTs = async() =>{
for(let i = 1; i <= edition; i++){
for (const layer of layers) await drawLayer(layer, i);
console.log("Creating edition " + i);
};
};
Final Code:
for(let i = 1; i <= edition; i++){
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (const layer of layers) await drawLayer(layer, i);
console.log("Creating edition " + i);
};
You have a forEach calling an async function.
forEach and async do not go together: the forEach is drawing the next image before the previous one is finished
Replace
layers.forEach(layer => {
drawLayer(layer, i);
});
with
for (const layer of layers) {
await drawLayer(layer, i);
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
(adding clear)
and put it in an async function

Collider in Phaser 3 randomly doesn't work

I just began coding in Phaser 3 after developing some games with p5.js and wanted to make a 2d endless runner game. So here's the code for my game:
var game;
var gameOptions = {
monkeyGravity: 1200,
monkeyPower: 1000
}
window.onload = function() {
let gameConfig = {
type: Phaser.AUTO,
backgroundColor:0x87ceeb,
scale: {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH,
parent: 'thegame',
width: 1920,
height: 1080
},
physics: {
default: 'arcade',
arcade: {debug: true}
},
scene: [
startGame,
playGame
]
}
game = new Phaser.Game(gameConfig);
window.focus();
}
class startGame extends Phaser.Scene{
constructor(){
super('StartGame');
}
preload(){
this.load.image('menu-bg', '/jeffrey2nd/menu-bg.png');
this.load.image('play-button', '/jeffrey2nd/play-button.png');
}
create() {
this.menuBg = this.add.sprite(game.config.width / 2, 0, 'menu-bg').setScale(2);
const screenCenterX = this.cameras.main.worldView.x + this.cameras.main.width / 2;
const screenCenterY = this.cameras.main.worldView.y + this.cameras.main.height / 2;
const startButton = this.add.sprite(screenCenterX, screenCenterY, 'play-button');
startButton.setInteractive();
startButton.on('pointerdown', () => this.scene.start('PlayGame'));
}
}
class playGame extends Phaser.Scene{
constructor(){
super('PlayGame');
}
preload(){
this.load.image('background', '/jeffrey2nd/background.png');
this.load.image('backgroundL1', '/jeffrey2nd/backgroundL1.png');
this.load.image('backgroundL2', '/jeffrey2nd/backgroundL2.png');
this.load.image('backgroundL3', '/jeffrey2nd/backgroundL3.png');
this.load.image('backgroundL4', '/jeffrey2nd/backgroundL4.png');
this.load.image('ground', '/jeffrey2nd/ground.png');
//ANIMATIONS
this.load.image('run0', '/jeffrey2nd/animations/monkey/Running_000.png');
this.load.image('run1', '/jeffrey2nd/animations/monkey/Running_001.png');
this.load.image('run2', '/jeffrey2nd/animations/monkey/Running_002.png');
this.load.image('run3', '/jeffrey2nd/animations/monkey/Running_003.png');
this.load.image('run4', '/jeffrey2nd/animations/monkey/Running_004.png');
this.load.image('run5', '/jeffrey2nd/animations/monkey/Running_005.png');
this.load.image('run6', '/jeffrey2nd/animations/monkey/Running_006.png');
this.load.image('run7', '/jeffrey2nd/animations/monkey/Running_007.png');
this.load.image('run8', '/jeffrey2nd/animations/monkey/Running_008.png');
this.load.image('run9', '/jeffrey2nd/animations/monkey/Running_009.png');
this.load.image('run10', '/jeffrey2nd/animations/monkey/Running_010.png');
this.load.image('run11', '/jeffrey2nd/animations/monkey/Running_011.png');
this.load.image('run12', '/jeffrey2nd/animations/monkey/Running_012.png');
this.load.image('run13', '/jeffrey2nd/animations/monkey/Running_013.png');
this.load.image('jump0', '/jeffrey2nd/animations/monkey/Jumping_000.png');
this.load.image('jump1', '/jeffrey2nd/animations/monkey/Jumping_001.png');
this.load.image('jump2', '/jeffrey2nd/animations/monkey/Jumping_002.png');
this.load.image('jump3', '/jeffrey2nd/animations/monkey/Jumping_003.png');
this.load.image('jump4', '/jeffrey2nd/animations/monkey/Jumping_004.png');
}
create(){
//BACKGROUND AND LAYERS
this.bgLs = this.add.group();
this.background = this.bgLs.create(0, game.config.height / 2, 'background');
this.backgroundL1 = this.bgLs.create(0, game.config.height / 2, 'backgroundL1');
this.backgroundL12 = this.bgLs.create(game.config.width, game.config.height / 2, 'backgroundL1');
this.backgroundL2 = this.bgLs.create(0, game.config.height / 2, 'backgroundL2');
this.backgroundL22 = this.bgLs.create(game.config.width, game.config.height / 2, 'backgroundL2');
this.backgroundL3 = this.bgLs.create(0, game.config.height / 2, 'backgroundL3');
this.backgroundL32 = this.bgLs.create(game.config.width, game.config.height / 2, 'backgroundL3');
this.backgroundL4 = this.bgLs.create(0, game.config.height / 2, 'backgroundL4');
this.backgroundL42 = this.bgLs.create(game.config.width, game.config.height / 2, 'backgroundL4');
for (let b of this.bgLs.children.entries) {
b.setOrigin(0, 0.5);
}
//GROUND PLATFORMS
this.groundGroup = this.physics.add.group();
this.ground1 = this.groundGroup.create(0, game.config.height - 50, 'ground');
this.ground2 = this.groundGroup.create(game.config.width, game.config.height - 50, 'ground');
this.ground3 = this.groundGroup.create(game.config.width + game.config.width / 2, game.config.height - 275, 'ground');
this.ground4 = this.groundGroup.create(game.config.width + game.config.width / 1.5, game.config.height - 500, 'ground');
this.ground4.setScale(0.5, 1);
for (let g of this.groundGroup.children.entries) {
g.setOrigin(0, 0.5);
g.setImmovable(true);
g.setScale(1,0.3);
g.body.checkCollision.down = false;
}
//MONKEY
this.monkey = this.physics.add.sprite(game.config.width / 10 * 2, 500, 'run0');
this.monkey.setScale(0.3);
this.anims.create({
key: "player-run",
frames: [
{ key: 'run0' },
{ key: 'run1' },
{ key: 'run2' },
{ key: 'run3' },
{ key: 'run4' },
{ key: 'run5' },
{ key: 'run6' },
{ key: 'run7' },
{ key: 'run8' },
{ key: 'run9' },
{ key: 'run10' },
{ key: 'run11' },
{ key: 'run12' },
{ key: 'run13' }
],
frameRate: 20,
repeat: -1
})
this.anims.create({
key: "player-jump",
frames: [
{ key: 'jump0' },
{ key: 'jump1' },
{ key: 'jump2' },
{ key: 'jump3' },
{ key: 'jump4' }
],
frameRate: 20,
repeat: -1
})
this.monkey.body.setSize(this.monkey.width/2, this.monkey.height/2);
this.input.on('pointerdown', this.jump, this);
this.input.on('pointerup', this.fall, this);
}
update(){
this.backgroundL1.x -= 0.2;
this.backgroundL12.x -= 0.2;
this.backgroundL2.x -= 0.4;
this.backgroundL22.x -= 0.4;
this.backgroundL3.x -= 0.6;
this.backgroundL32.x -= 0.6;
this.backgroundL4.x -= 0.8;
this.backgroundL42.x -= 0.8;
for (let b of this.bgLs.children.entries) {
if (b.x <= -game.config.width) b.setX(game.config.width);
}
var speed = 5;
for (let g of this.groundGroup.children.entries) {
g.setX(g.x-speed);
//if (g.x <= -game.config.width) g.setX(game.config.width);
}
if (this.ground1.x <= -game.config.width) this.ground1.setX(game.config.width);
if (this.ground2.x <= -game.config.width) this.ground2.setX(game.config.width);
if (this.ground3.x <= -game.config.width) {
this.rnd1 = (Phaser.Math.Between(0, 500))/100;
this.ground3.setX(game.config.width + game.config.width / this.rnd1);
}
if (this.ground4.x <= -game.config.width) {
this.rnd2 = (Phaser.Math.Between(0, 500))/100;
this.ground4.setX(game.config.width + game.config.width / this.rnd2);
}
this.physics.world.collide(this.groundGroup, this.monkey, ()=> {console.log('touche' + game.loop.time )}, null, this);
this.monkey.body.gravity.y = gameOptions.monkeyGravity;
if(this.monkey.body.touching.down) this.monkey.anims.play("player-run", true);
else this.monkey.anims.play("player-jump", true);
}
jump(){
if(this.monkey.body.touching.down) {
this.monkey.body.setVelocity(0, -gameOptions.monkeyPower);
this.monkey.anims.stop();
this.monkey.anims.play("player-jump");
}
}
fall(){
if (this.monkey.body.velocity.y < 0) this.monkey.body.setVelocity(0, -100);
}
}
Game start scene has the Start Button, the game begins, the monkey runs on the platforms and you can jump on the upper platforms.
All seems to work fine, but sometimes randomly the monkey falls down off the screen.
You can see a playable version of the bug at https://420videogames.com/jeffrey2nd
Here I added a console log in the 'monkey vs ground goup collide' callback function, logging the game.loop.time to try to understand. My idea was that maybe some frames were missed during Update and the objects did not collide perfectly, but when the monkey falls off, the callback function runs 2 times and then the monkey keeps falling and the game breaks up.
Another strange thing about this issue is that on my mobile phone REDMI8 the game works with no problems, as for the iPhone8 of my GF. On Firefox mobile of another friend, by the way, the game has the same PC issue.
Thank you in advance for your attention, hope someone can help me fix this problem,
Ab
The issue was resolved moving the colliders from Update function to Create function.

How to make a three graph dynamic in HTML5, Css3 and Vanilla js?

I have constructed a tree graph using html5, css3 but the nodes are static. Now I wanna make that graph dynamic. Here dynamic means suppose the node count increases and there are multiple children, now the graph will be generated with the new nodes and children.
This is just an example using vanilla JavaScript. I've taken a lot of inspiration from d3, including how to store the data as a self-referencing tree of nodes and how to traverse the tree breadth-first.
I've tried to comment the code as well as possible, I hope this gives you some inspiration. I'd try to improve the positioning of the labels a bit, and/or increase the margins so they're better visible.
const data = [{
id: 0,
label: "Command Sequence Starting",
},
{
id: 1,
parents: [0],
label: "W_SCMadl_refresh",
status: "done",
},
{
id: 2,
parents: [1],
label: "W_adl_photo",
status: "done",
},
{
id: 3,
parents: [2],
label: "W_adl_collect",
status: "done",
},
{
id: 4,
parents: [3],
label: "W_adl_collect_cr",
status: "done",
},
{
id: 5,
parents: [4],
label: "W_adl_sync",
status: "aborted",
},
{
id: 6,
parents: [5],
label: "W_adl_attach",
status: "waiting",
},
{
id: 7,
parents: [6],
label: "W_adl_attach",
status: "waiting",
},
{
id: 8,
parents: [7],
label: "W_adl_publish",
status: "waiting",
},
{
id: 9,
parents: [8],
label: "W_adl_ds_ws",
status: "waiting",
},
{
id: 10,
parents: [9],
label: "W64_Shared_Preq_mkdir",
status: "waiting",
},
{
id: 11,
parents: [10, 12],
label: "W64_mkCopyPreq",
status: "waiting",
},
{
id: 12,
parents: [0],
label: "WIN64_MCCMon",
status: "done",
},
];
// Make the data array a self-referencing tree, where each node has pointers to their
// parents and their children nodes
data
.filter(d => d.parents !== undefined)
.forEach(d => {
d.parents = data.filter(p => d.parents.includes(p.id));
d.parents.forEach(p => {
if (p.children === undefined) {
p.children = [];
}
p.children.push(d);
});
});
const root = data.find(d => d.parents === undefined);
// Breadth first traversal of the tree, excuting `fn` for every node
const forEach = (root, fn) => {
const stack = [root];
while (stack.length) {
const current = stack.shift();
if (current.children) {
stack.push(...current.children);
}
fn(current);
}
};
const svg = document.querySelector(".mv-sequence svg");
const margin = {
top: 20,
bottom: 20,
right: 20,
left: 20,
};
const width = +svg.getAttribute("width") - margin.left - margin.right;
const stepHeight = 40;
const namespace = "http://www.w3.org/2000/svg";
const gContainer = document.createElementNS(namespace, "g");
gContainer.setAttribute("transform", `translate(${margin.left},${margin.top})`);
svg.appendChild(gContainer);
const linksContainer = document.createElementNS(namespace, "g");
gContainer.appendChild(linksContainer);
const nodesContainer = document.createElementNS(namespace, "g");
gContainer.appendChild(nodesContainer);
// Give node a level. First complete this loop, then start drawing, because we want to
// be robust against not all parents having a level yet
forEach(
root,
d => {
if (d === root) {
d.level = 0;
return;
}
d.level = Math.max(...d.parents.map(p => p.level)) + 1;
}
);
forEach(
root,
d => {
// Position the node based on the number of siblings.
const siblings = data.filter(n => n.level === d.level);
// If the node is an only child. The root should be in the centre,
// any other node should be in the average of it's parents
if (siblings.length === 1) {
if (d.parents === undefined) {
d.x = width / 2;
} else {
d.x = d.parents.map(p => p.x).reduce((s, v) => s + v, 0) / d.parents.length;
}
return;
}
// Otherwise, divide the space evenly for all sibling nodes
const siblingIndex = siblings.indexOf(d);
const stepWidth = width / (siblings.length - 1);
if (siblings.length % 2 === 0) {
// Even number of siblings
d.x = stepWidth * siblingIndex;
} else {
// Odd number of siblings, the center one must be in the middle
d.x = width / 2 + stepWidth * (siblingIndex - (siblings.length - 1) / 2);
}
}
);
forEach(
root,
d => {
// Append a circle and `text` for all new nodes
d.y = d.level * stepHeight;
const nodeContainer = document.createElementNS(namespace, "g");
nodeContainer.setAttribute("transform", `translate(${d.x}, ${d.y})`);
nodeContainer.classList.add("mv-command", d.status);
nodesContainer.appendChild(nodeContainer);
const circle = document.createElementNS(namespace, "circle");
circle.setAttribute("r", stepHeight / 4);
nodeContainer.appendChild(circle);
const label = document.createElementNS(namespace, "text");
label.setAttribute("dx", stepHeight / 4 + 5);
label.textContent = d.label;
nodeContainer.appendChild(label);
// Append a link from every parent to this node
(d.parents || []).forEach(p => {
const link = document.createElementNS(namespace, "path");
let path = `M${p.x} ${p.y}`;
let dx = d.x - p.x;
let dy = d.y - p.y;
if (dy > stepHeight) {
// Move down to the level of the child node
path += `v${dy - stepHeight}`;
dy = stepHeight;
}
path += `s0 ${dy / 2}, ${dx / 2} ${dy / 2}`;
path += `s${dx / 2} 0, ${dx / 2} ${dy / 2}`;
link.setAttribute("d", path)
linksContainer.appendChild(link);
})
}
);
// Finally, set the height to fit perfectly
svg.setAttribute("height", Math.max(...data.map(d => d.level)) * stepHeight + margin.top + margin.bottom);
.mv-command.done {
fill: #477738;
}
.mv-command.aborted {
fill: #844138;
}
.mv-command.waiting {
fill: #808080;
}
.mv-command.disabled {
fill: #80808080;
}
.mv-command.running {
fill: #005686;
animation: mymove 2s infinite;
}
.mv-command>text {
dominant-baseline: middle;
font-size: 12px;
}
path {
fill: none;
stroke: darkgreen;
stroke-width: 3px;
}
<div class="mv-sequence">
<svg width="200"></svg>
</div>

Google Apps Script does not recognize tables in my document

First of all, I would like to thank you for your help in solving problems prior to this project, which was of great value in solving past problems.
I'm working with google apps script to format the titles of a document within tables.
The normal text is this:
After the script runs it looks like this:
The script is inserting the text inside tables in a normal way, as desired, however in addition to this formatting, I need to style the titles. Example: Title 1 usually has an Arial 18 font, without boldface and I want to change that to a Roboto 18 font with boldface.
I tried to work with custom styles of google apps, but in the script processing the formatting is lost specifically when it passes through this line of code.
I have already tried to recover the tables and format them after the update process, but the system does not recognize the tables as tables after the update process, and only the last formatted title remains in the desired format, as shown in the second image. See some prints of my debugging process.
The first title is changed and placed within the table and the formatting is applied and the inserted table is recognized:
When the script reaches the saveAndClose () point of the second method, the customization of the previous title disappears:
At the end of the process, only the last customized title remains in the desired format.
I already tried to recover the inserted tables to perform the update in the style of the text of the second column, but the script does not recognize the tables. It recognizes only one, and in fact, in this document I have 4 tables.
Here is a script for verification:
function verifiStyle(){
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragrafs = body.getParagraphs();
for(var i = paragrafs.length - 1; i >= 0; i--){
var attr = paragrafs[i].getAttributes();
for(var at in attr){
if(at == "HEADING" & attr[at] == "HEADING1"){
VerifTitle1(i);
}
else if(at == "HEADING" & attr[at] == "HEADING2"){
VerifTitle2(i);
}
else if(at == "HEADING" & attr[at] == "HEADING3"){
VerifTitle3(i);
}
else if(at == "HEADING" & attr[at] == "HEADING4"){
VerifTitle4(i);
}
else if(at == "HEADING" & attr[at] == "NORMAL"){
VerifTextoNormal(i);
}
}
}
var tables = body.getTables();
}
function VerifTitle1(value){
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var texto = body.getChild(value);
var ttt = texto.getText();
var cells = [
['', '']
];
var styleCell1 = {};
styleCell1[DocumentApp.Attribute.FONT_SIZE] = 20;
styleCell1[DocumentApp.Attribute.VERTICAL_ALIGNMENT] = DocumentApp.VerticalAlignment.CENTER;
styleCell1[DocumentApp.Attribute.FOREGROUND_COLOR]='#888888';
styleCell1[DocumentApp.Attribute.FONT_FAMILY]='Roboto';
var styleCell = {};
styleCell[DocumentApp.Attribute.VERTICAL_ALIGNMENT] = DocumentApp.VerticalAlignment.CENTER;
styleCell[DocumentApp.Attribute.FONT_FAMILY]='Roboto';
styleCell[DocumentApp.Attribute.FONT_SIZE] = 18;
styleCell[DocumentApp.Attribute.FOREGROUND_COLOR]='#000000';
styleCell[DocumentApp.Attribute.HEIGHT] = 0.5;
body.removeChild(body.getChild(value));
var table = body.insertTable(value, cells);
table.getRow(0).getCell(1).appendParagraph(ttt).setHeading(DocumentApp.ParagraphHeading.HEADING2);
table.getRow(0).getCell(1).setAttributes(styleCell);
table.getRow(0).getCell(0).setWidth(2);
table.getRow(0).getCell(0).setAttributes(styleCell1);
table.setBorderColor('#ffffff');
table.getRow(0).editAsText().setBold(true);
const index = body.getChildIndex(table);
const documentId = doc.getId();
doc.saveAndClose();
const tableStart = Docs.Documents.get(documentId).body.content[index + 1].startIndex;
const tempStyle = {width: {magnitude :0, unit: "PT"}, dashStyle: "SOLID", color: {color: {rgbColor: {blue: 0}}}};
const resource = {requests: [
{updateTableCellStyle: {
tableStartLocation: {index: tableStart},
tableCellStyle: {borderTop: tempStyle, borderBottom: tempStyle, borderLeft: tempStyle, borderRight: tempStyle},
fields: "borderTop,borderBottom,borderLeft,borderRight"
}},
{updateTableCellStyle: {
tableRange: {
tableCellLocation: {tableStartLocation: {index: tableStart}, rowIndex: 0, columnIndex: 0}, rowSpan: 1, columnSpan: 1},
tableCellStyle: {
borderRight: {dashStyle: "SOLID", width: {magnitude: 3, unit: "PT"}, color: {color: {rgbColor: {red: 0.9372549019607843, green: 0.3254901960784314, blue: 0.3137254901960784}}}}
},
fields: "borderRight"
}}
]};
Docs.Documents.batchUpdate(resource, documentId);
table = body.getChild(value).asTable();
}
function VerifTitle2(value){
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var texto = body.getChild(value);
var ttt = texto.getText();
var cells = [
['', '']
];
var styleCell1 = {};
styleCell1[DocumentApp.Attribute.FONT_SIZE] = 18;
styleCell1[DocumentApp.Attribute.VERTICAL_ALIGNMENT] = DocumentApp.VerticalAlignment.CENTER;
styleCell1[DocumentApp.Attribute.FOREGROUND_COLOR]='#888888';
styleCell1[DocumentApp.Attribute.FONT_FAMILY]='Roboto';
var styleCell = {};
styleCell[DocumentApp.Attribute.VERTICAL_ALIGNMENT] = DocumentApp.VerticalAlignment.CENTER;
styleCell[DocumentApp.Attribute.FONT_FAMILY]='Roboto';
styleCell[DocumentApp.Attribute.FONT_SIZE] = 15;
styleCell[DocumentApp.Attribute.FOREGROUND_COLOR]='#000000';
styleCell[DocumentApp.Attribute.HEIGHT] = 0.5;
body.removeChild(body.getChild(value));
var table = body.insertTable(value, cells);
table.getRow(0).getCell(1).appendParagraph(ttt).setHeading(DocumentApp.ParagraphHeading.HEADING2);
table.getRow(0).getCell(1).setAttributes(styleCell);
table.getRow(0).getCell(0).setWidth(2);
table.getRow(0).getCell(0).setAttributes(styleCell1);
table.setBorderColor('#ffffff');
table.getRow(0).editAsText().setBold(true);
const index = body.getChildIndex(table);
const documentId = doc.getId();
doc.saveAndClose();
const tableStart = Docs.Documents.get(documentId).body.content[index + 1].startIndex;
const tempStyle = {width: {magnitude :0, unit: "PT"}, dashStyle: "SOLID", color: {color: {rgbColor: {blue: 0}}}};
const resource = {requests: [
{updateTableCellStyle: {
tableStartLocation: {index: tableStart},
tableCellStyle: {borderTop: tempStyle, borderBottom: tempStyle, borderLeft: tempStyle, borderRight: tempStyle},
fields: "borderTop,borderBottom,borderLeft,borderRight"
}},
{updateTableCellStyle: {
tableRange: {
tableCellLocation: {tableStartLocation: {index: tableStart}, rowIndex: 0, columnIndex: 0}, rowSpan: 1, columnSpan: 1},
tableCellStyle: {
borderRight: {dashStyle: "SOLID", width: {magnitude: 3, unit: "PT"}, color: {color: {rgbColor: {red: 0.9372549019607843, green: 0.3254901960784314, blue: 0.3137254901960784}}}}
},
fields: "borderRight"
}}
]};
Docs.Documents.batchUpdate(resource, documentId);
}
function VerifTitle3(value){
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var texto = body.getChild(value);
var ttt = texto.getText();
var cells = [
['', '']
];
var styleCell1 = {};
styleCell1[DocumentApp.Attribute.FONT_SIZE] = 16;
styleCell1[DocumentApp.Attribute.VERTICAL_ALIGNMENT] = DocumentApp.VerticalAlignment.CENTER;
styleCell1[DocumentApp.Attribute.FOREGROUND_COLOR]='#888888';
styleCell1[DocumentApp.Attribute.FONT_FAMILY]='Roboto';
var styleCell = {};
styleCell[DocumentApp.Attribute.VERTICAL_ALIGNMENT] = DocumentApp.VerticalAlignment.CENTER;
styleCell[DocumentApp.Attribute.FONT_FAMILY]='Roboto';
styleCell[DocumentApp.Attribute.FONT_SIZE] = 14;
styleCell[DocumentApp.Attribute.FOREGROUND_COLOR]='#000000';
styleCell[DocumentApp.Attribute.HEIGHT] = 0.5;
styleCell[DocumentApp.Attribute.BOLD] = true;
body.removeChild(body.getChild(value));
var table = body.insertTable(value, cells);
table.getRow(0).getCell(1).appendParagraph(ttt).setHeading(DocumentApp.ParagraphHeading.HEADING3);
table.getRow(0).getCell(1).setAttributes(styleCell);
table.getRow(0).getCell(0).setWidth(2);
table.getRow(0).getCell(0).setAttributes(styleCell1);
table.setBorderColor('#ffffff');
table.getRow(0).editAsText().setBold(true);
const index = body.getChildIndex(table);
const documentId = doc.getId();
doc.saveAndClose();
const tableStart = Docs.Documents.get(documentId).body.content[index + 1].startIndex;
const tempStyle = {width: {magnitude :0, unit: "PT"}, dashStyle: "SOLID", color: {color: {rgbColor: {blue: 0}}}};
const resource = {requests: [
{updateTableCellStyle: {
tableStartLocation: {index: tableStart},
tableCellStyle: {borderTop: tempStyle, borderBottom: tempStyle, borderLeft: tempStyle, borderRight: tempStyle},
fields: "borderTop,borderBottom,borderLeft,borderRight"
}},
{updateTableCellStyle: {
tableRange: {
tableCellLocation: {tableStartLocation: {index: tableStart}, rowIndex: 0, columnIndex: 0}, rowSpan: 1, columnSpan: 1},
tableCellStyle: {
borderRight: {dashStyle: "SOLID", width: {magnitude: 3, unit: "PT"}, color: {color: {rgbColor: {red: 0.9372549019607843, green: 0.3254901960784314, blue: 0.3137254901960784}}}}
},
fields: "borderRight"
}}
]};
Docs.Documents.batchUpdate(resource, documentId);
}
function VerifTitle4(value){
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var texto = body.getChild(value);
var ttt = texto.getText();
var cells = [
['', '']
];
var styleCell1 = {};
styleCell1[DocumentApp.Attribute.FONT_SIZE] = 14;
styleCell1[DocumentApp.Attribute.VERTICAL_ALIGNMENT] = DocumentApp.VerticalAlignment.CENTER;
styleCell1[DocumentApp.Attribute.FOREGROUND_COLOR]='#888888';
styleCell1[DocumentApp.Attribute.FONT_FAMILY]='Roboto';
var styleCell = {};
styleCell[DocumentApp.Attribute.VERTICAL_ALIGNMENT] = DocumentApp.VerticalAlignment.CENTER;
styleCell[DocumentApp.Attribute.FONT_FAMILY]='Roboto';
styleCell[DocumentApp.Attribute.FONT_SIZE] = 12;
styleCell[DocumentApp.Attribute.FOREGROUND_COLOR]='#000000';
styleCell[DocumentApp.Attribute.HEIGHT] = 0.5;
body.removeChild(body.getChild(value));
var table = body.insertTable(value, cells);
var tables = body.getTables();
table.getRow(0).getCell(1).appendParagraph(ttt).setHeading(DocumentApp.ParagraphHeading.HEADING2);
table.getRow(0).getCell(1).setAttributes(styleCell);
table.getRow(0).getCell(0).setWidth(2);
table.getRow(0).getCell(0).setAttributes(styleCell1);
table.setBorderColor('#ffffff');
table.getRow(0).editAsText().setBold(true);
const index = body.getChildIndex(table);
const documentId = doc.getId();
doc.saveAndClose();
const tableStart = Docs.Documents.get(documentId).body.content[index + 1].startIndex;
const tempStyle = {width: {magnitude :0, unit: "PT"}, dashStyle: "SOLID", color: {color: {rgbColor: {blue: 0}}}};
const resource = {requests: [
{updateTableCellStyle: {
tableStartLocation: {index: tableStart},
tableCellStyle: {borderTop: tempStyle, borderBottom: tempStyle, borderLeft: tempStyle, borderRight: tempStyle},
fields: "borderTop,borderBottom,borderLeft,borderRight"
}},
{updateTableCellStyle: {
tableRange: {
tableCellLocation: {tableStartLocation: {index: tableStart}, rowIndex: 0, columnIndex: 0}, rowSpan: 1, columnSpan: 1},
tableCellStyle: {
borderRight: {dashStyle: "SOLID", width: {magnitude: 3, unit: "PT"}, color: {color: {rgbColor: {red: 0.9372549019607843, green: 0.3254901960784314, blue: 0.3137254901960784}}}}
},
fields: "borderRight"
}}
]};
Docs.Documents.batchUpdate(resource, documentId);
var tables1 = body.getTables();
}
function VerifTextoNormal(value){
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var para = body.getParagraphs();
var styleCell = {};
styleCell[DocumentApp.Attribute.HEADING] = DocumentApp.ParagraphHeading.NORMAL;
styleCell[DocumentApp.Attribute.VERTICAL_ALIGNMENT] = DocumentApp.VerticalAlignment.CENTER;
styleCell[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.JUSTIFY;
styleCell[DocumentApp.Attribute.FONT_FAMILY]='Arial';
styleCell[DocumentApp.Attribute.FONT_SIZE] = 12;
styleCell[DocumentApp.Attribute.FOREGROUND_COLOR]='#000000';
styleCell[DocumentApp.Attribute.INDENT_FIRST_LINE] = 15;
para[value].setAttributes(styleCell);
}
How about this answer?
Issue and workaround:
I could confirm the same issue using your shared sample Google Document. In this case, after updateTables() was finished, it seems that getTables() doesn't return the tables in the Document body. I think that this might be a bug. I thought that this might also affect to the current issue. So, in order to avoid this issue, I would like to propose to use Docs API.
At your script, when verifiStyle() is run, it updates the tables at the last line of verifiStyle(). This is a workaround.
Modified script:
When your script is modified, please modify as follows.
From:
This is the script in the last line of the function verifiStyle().
var tables = body.getTables();
}
To:
updateTables(); // Modified
}
// Added the below function.
function updateTables() {
const docId = DocumentApp.getActiveDocument().getId();
const contents = Docs.Documents.get(docId).body.content;
const reqs = contents.reduce((ar, e) => {
if ("table" in e) {
const t = e.table.tableRows[0].tableCells;
const obj = [
{updateTextStyle: {
range: {startIndex: t[0].startIndex, endIndex: t[0].endIndex},
textStyle: {bold: true, fontSize: {magnitude: 20, unit: "PT"}, weightedFontFamily: {fontFamily: "Roboto"}},fields: "bold,fontSize,weightedFontFamily"}
},
{updateTextStyle: {
range: {startIndex: t[1].startIndex, endIndex: t[1].endIndex},
textStyle: {bold: true, fontSize: {magnitude: 18, unit: "PT"}, weightedFontFamily: {fontFamily: "Roboto"}}, fields: "bold,fontSize,weightedFontFamily"}
}
];
ar = [...ar, obj];
}
return ar;
}, []);
Docs.Documents.batchUpdate({requests: reqs}, docId);
}
References:
Method: documents.batchUpdate
UpdateTextStyleRequest

EaselJs performance issue for many sprite classes

I would like to ask whether does easeljs has performance issue for many sprite class objects? It seems that from my codepen demo, its terribly lagging...below's code as follows:
var $window = $(window),
wh = $window.innerHeight(),
ww = $window.innerWidth();
var stage = new createjs.Stage("sceneStage");
var w, h, drone;
var runnerSprite2, runnerContainer, drone2, droneContainer, robot;
var robot__movement_speed = 1;
var building_right, building_left;
var queue = new createjs.LoadQueue(),
$state = $('#state'),
$progress = $('#progress'),
$progressbar = $('#progressbar .bar');
queue.on('complete', onComplete);
queue.on('error', onError);
queue.on('fileload', onFileLoad);
queue.on('fileprogress', onFileProgress);
queue.on('progress', onProgress);
queue.loadManifest([
{
id: '2',
src: 'images/sprite_robot_test_plus_toss.png'
},
{
id: '3',
src: 'images/Drones-Hovering-Loop-12fps.png'
},
{
id: '4',
src: 'images/sprite_robot_plus_toss.png'
},
{
id: '5',
src: 'images/sprite_protestor.png'
}
]);
function onComplete(event) {
console.log('Complete', event);
$state.text( $state.text() + '[All loaded]' );
$progressbar.addClass('complete');
$('#mainContainer').addClass('hide');
$('#drone').removeClass('hidden');
loadScenes();
}
function onError(event) {
console.log('Error', event);
$state.text( $state.text() + '[' + event + ' errored] ');
}
function onFileLoad(event) {
console.log('File loaded', event);
$state.text( $state.text() + '[' + event.item.id + ' loaded] ');
}
function onFileProgress(event) {
console.log('File progress', event);
}
function onProgress(event) {
var progress = Math.round(event.loaded * 100);
console.log('General progress', Math.round(event.loaded) * 100, event);
$progress.text(progress + '%');
$progressbar.css({
'width': progress + '%'
});
}
function loadScenes() {
// grab canvas width and height for later calculations:
stage.canvas.width = window.innerWidth;
stage.canvas.height = window.innerHeight;
w = stage.canvas.width;
h = stage.canvas.height;
//----- Drones --------//
var data = new createjs.SpriteSheet({
"images": ["images/Drones-Hovering-Loop-12fps.png"],
"frames": {"regX": 0, "height": 262, "count": 25, "regY": 0, "width": 250},
"animations": {
"idle": [0, 24],
"stun": [0, 0]
},
framerate: 24
});
drone = new createjs.Sprite(data, "idle");
drone.setBounds(null, null, 250, 262);
drone.y = h - drone.getBounds().height;
drone.x = w - drone.getBounds().width;
building_right = drone;
var drone_left = new createjs.Sprite(data, "stun");
drone_left.setBounds(null, null, 250, 262);
drone_left.regX = 250;
drone_left.y = h - drone_left.getBounds().height;
drone_left.x = drone_left.regX;
building_left = drone_left;
droneContainer = new createjs.Container();
droneContainer.addChild(drone, drone_left);
stage.addChild(droneContainer, runnerContainer);
var robot_walk_left_arry = [],
robot_walk_right_arry = [];
for(var i = 14; i< 50; i++) {
robot_walk_left_arry.push(i);
}
for(var i = 49; i > 13; i--) {
robot_walk_right_arry.push(i);
}
console.log(robot_walk_right_arry);
var robot_data = new createjs.SpriteSheet({
"images": ["images/sprite_robot_test_plus_toss.png"],
"frames": {"regX": 0, "height": 540, "count": 83, "regY": 0, "width": 810},
"animations": {
idle: {
frames: [0,1,2,3,4,5,6,7,8,9,10,11,12,11,10,9,8,7,6,5,4,3,2,1]
},
walk_left: {
frames: robot_walk_left_arry,
speed: 1 * robot__movement_speed
},
walk_right: {
frames: robot_walk_right_arry,
speed: 1 * robot__movement_speed
},
toss_left: [50, 82, "idle", 0.8 * robot__movement_speed]
},
framerate: 24
});
robot = new createjs.Sprite(robot_data, "idle");
robot.setBounds(null, null, 810, 540);
robot.regX = 405;
robot.x = (w - robot.getBounds().width);
robot.y = h - robot.getBounds().height;
robot._body_dimen = 162;
stage.addChild(robot);
var protestor_data = new createjs.SpriteSheet({
"images": ["images/sprite_protestor.png"],
"frames": {"regX": 0, "height": 216, "count": 39, "regY": 0, "width": 384},
"animations": {
idle: {
frames: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,13,12,11,10,9,8,7,6,5,4,3,2,1]
},
recovery: [33, 38, "idle", 1],
nudge: [15,33, "recovery", 1]
},
framerate: 24
});
var protestor = new createjs.Sprite(protestor_data, "idle");
protestor.setBounds(null, null, 384, 216);
protestor.x = 200;
protestor.y = h - protestor.getBounds().height;
stage.addChild(protestor);
drone_left.on("click", function() {
tweenthis(robot, robot.x, "left");
});
drone.on("click", function() {
tweenthis(robot, robot.x, "right");
});
createjs.Ticker.framerate = 30;
createjs.Ticker.timingMode = createjs.Ticker.RAF;
createjs.Ticker.addEventListener("tick", tick);
// createjs.Ticker.on("tick", stage);
}
function handleClick(evt, data) {
console.log('test');
}
function tick(event) {
stage.update(event);
}
Generally I just create 4 sprite classes with 3 different sprite images. But didn't expect it to be running so lagging.
The protestors image seems to be 8k x 8k pixel in size (with only the top part filled apparently)... That's about 192 MB unpacked... That will bring down any engine... Make sure your animation images are more efficiently packed and of a more reasonable size...

Categories