Custom Updates
Task
Create sprites moving in spiral path away from the center. Use a ball class derived from ImageSprite, having a custom update function.
Result
JavaScript
// Demo 10
const 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
var sprites = {
"blueBall" : { sx : 616, sy : 200, sw : 200, sh : 200 },
"grayBall" : { sx : 816, sy : 200, sw : 200, sh : 200 },
"redBall" : { sx : 1216, 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 a 'Ball' class
class Ball extends grayFrog.SheetSprite {
constructor(name, x, y, sheet, frameSpecs, direction, radius) {
super(name, x, y, sheet, frameSpecs);
this._direction = direction;
this._radius = radius;
}
_customUpdate(elapsed) {
this.x = this.parent.midX + this._radius * Math.cos(this._direction);
this.y = this.parent.midY + this._radius * Math.sin(this._direction);
this._direction += elapsed / 3000;
this._radius += elapsed / 30;
this.handleEdgeBehaviour();
}
}
// Create an infinite stream of balls
const ballNames = ["redBall", "grayBall", "blueBall"];
const nb = ballNames.length;
let direction = 0;
let count = 0;
setInterval(() => {
let spriteName = ballNames[count % nb];
let ball = new Ball('ball_' + count++,
scene.midX, scene.midY,
imageDictionary.spritesheet, sprites[spriteName],
direction, 0);
ball.scale = 0.1;
ball.edgeBehaviour = grayFrog.EDGE_BEHAVIOUR.remove;
direction += Math.PI / 12;
scene.addChild(ball);
}, 10);
// Start the game loop
controller.start();
}