Position Updates

Task

Create a random number of ball sprites, give each of them a random direction and speed and let them move within the canvas. All balls will bump off the walls.

Result

JavaScript

// Demo 9

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
    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 = 100 + Math.floor(Math.random() * 1901);
    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,
            scene.midX, scene.midY,
            imageDictionary.spritesheet,
            sprites[spriteName]);
        ball.scale = 0.1 + Math.random() * 0.9;
        ball.angle = Math.random() * 360;
        ball.speed = 10 + Math.random() * 191;
        ball.positionAutoUpdate = true;
        ball.edgeBehaviour = grayFrog.EDGE_BEHAVIOUR.bounce;
        scene.addChild(ball);
    }   

    // Start the game loop
    controller.start();
}