Using a Spritesheet
Task
Create a random number of sprites, where the images are taken from a spritesheet.
Result
JavaScript
// Demo 5
let grayFrog = makeGrayFrogLibrary();
function start() {
// Load images and start demo when loading has finished
let ip = new grayFrog.ImagePreloader();
ip.preloadImages(
[
{ name: 'spritesheet', source: 'images/sprites.png' }
],
() => demo(ip.imageDictionary)
);
}
function demo(imageDictionary) {
// Spritesheet data
let sprites = {
'blueBall' : { sx : 616, sy : 200, sw : 200, sh : 200 },
'grayBall' : { sx : 816, sy : 200, sw : 200, sh : 200 },
'greenBall' : { sx : 1016, sy : 0, sw : 200, sh : 200 },
'orangeBall' : { sx : 1016, sy : 200, sw : 200, sh : 200 },
'purpleBall' : { sx : 1216, sy : 0, sw : 200, sh : 200 },
'redBall' : { sx : 1216, sy : 200, sw : 200, sh : 200 },
'yellowBall' : { sx : 1416, sy : 200, sw : 200, sh : 200 }
};
// Initialize canvas, controller, and scene
let canvas = document.getElementById('demoCanvas');
let controller = new grayFrog.Controller(canvas, true);
let scene = controller.makeDrawnScene('main', '#ffffff');
controller.scene = scene;
// Make sprites
const n = 10 + Math.floor(Math.random() * 91);
let ballNames = Object.keys(sprites);
let nb = ballNames.length;
for (let i = 0; i < n; i++) {
let spriteName = ballNames[Math.floor(Math.random() * nb)];
let ball = new grayFrog.SheetSprite('ball_' + i,
Math.floor(Math.random() * scene.width),
Math.floor(Math.random() * scene.height),
imageDictionary.spritesheet,
sprites[spriteName]);
ball.scale = 0.1 + Math.random() * 0.9;
scene.addChild(ball);
}
// Start the game loop
controller.start();
}