Wrap Around

Task

Create a box which has several balls as its children. Move the box from left to right within the scene and let it wrap around the edges.

Result

JavaScript

// Demo 13

const grayFrog = makeGrayFrogLibrary();

function start() {
    // Load images and start demo when loading has finished    
    let ip = new grayFrog.ImagePreloader();
    ip.preloadImages(
        [
            { name: 'grid', source: 'images/grid.png' },
            { name: 'quarterGrid', source: 'images/quarterGrid.png' },
            { 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.makeImageScene('main', imageDictionary.grid);
    controller.scene = scene;

    // Add a box to the scene, make it rotate and move across the scene
    let box = new grayFrog.DrawnSprite(
        'box', scene.midX, scene.midY, 240, 240);
    box.customDraw = function() {
        this.drawRectangleOutline('#ffffff', '#000000', 3, 1, 1);
    };
    box.speed = 100;
    box.positionAutoUpdate = true;
    box.edgeBehaviour = grayFrog.EDGE_BEHAVIOUR.wraparaound;
    box.addAction(new grayFrog.Action('rotation', 360, 10,
        grayFrog.EASING.linear,
        { atEndBehaviour: grayFrog.ACTION_AT_END_BEHAVIOUR.repeat }));
    scene.addChild(box);

    // Add moving balls to the box
    let ballNames = Object.keys(sprites);
    let nb = ballNames.length;
    for (let i = 0; i < 10; i++) {
        let spriteName = ballNames[Math.floor(Math.random() * nb)];
        let ball = new grayFrog.SheetSprite('ball_' + i,
            box.midX, box.midY,
            imageDictionary.spritesheet,
            sprites[spriteName]);
        ball.scale = 0.2 + Math.random() * 0.3;
        ball.angle = Math.random() * 360;
        ball.speed = 20 + Math.random() * 60;
        ball.hasCircularShape = true;
        ball.positionAutoUpdate = true;
        ball.edgeBehaviour = grayFrog.EDGE_BEHAVIOUR.bounce;
        box.addChild(ball);
    }   

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