DEV Community

Tetragius
Tetragius

Posted on

Use CSS animation for game in js (just for fun)

When an element moves with the help of CSS animation, we can read its real coordinates in the JS code and use it in calculations. Thus css is engaged in animation, and JS - collision calculation.

Animation for block

@keyframes animation-a { 
    0% { 
       left: 400px;
    }
    50% { 
       left: 200px;
    }
    100% { 
       left: 400px;
    }
}

Blocks array

const blocks = [  // left, bottom, width, animation-name, duration
    [240, 240, 700, null],
    [0, 180, 200, null],
    [400, 140, 100, 'animation-a', 5],
    [400, 90, 250, null],
    [250, 40, 150, 'animation-b', 3],
    [0, 0, 250, null],
    [400, 0, 670, null],
    [0, -40, 700, null],
];

Prepare blocks for scene

function prepareBlocks() {
    for (let b in blocks) {
        let _block = blocks[b];
        let block = document.createElement('div');
        block.classList.add('block');
        block.style.left = `${_block[0]}px`;
        block.style.bottom = `${_block[1]}px`;
        block.style.width = `${_block[2]}px`;
        block.style.animationName = _block[3] || '';
        block.style.animationDuration = `${_block[4]}s` || '';
        scene.insertBefore(block, player);
        blocks[b] = block;
    }
}


`

Top comments (3)

Collapse
 
georgecoldham profile image
George

If you added this to CodePen you could embed the code and demo into your post FYI 👍

Its a cool little game, you can jump through the floor by head-butting the ceiling though!

Collapse
 
tetragius profile image
Tetragius

Thank you!

Collapse
 
thomasbnt profile image
Thomas Bnt ☕

Great 👍