Build Your Own HTML Platformer: A Beginner's Guide
<!DOCTYPE html>
<html>
<head>
<title>Build Your Own HTML Platformer</title>
<style>
#gameContainer {
width: 500px;
height: 500px;
border: 2px solid black;
}
</style>
</head>
<body>
<div id='gameContainer'></div>
<pre><code><script>
var canvas = document.getElementById('gameContainer');
var ctx = canvas.getContext('2d');
// GAME OBJECT
var game = {
x: 0,
y: 0,
width: 500,
height: 500,
player: {
x: 0,
y: 0,
width: 30,
height: 30,
speed: 5
},
platforms: [
{x: 0, y: 350, width: 100, height: 20},
{x: 200, y: 250, width: 100, height: 20},
{x: 350, y: 350, width: 100, height: 20},
],
draw: function() {
ctx.fillStyle = 'black';
ctx.fillRect(this.x, this.y, this.width, this.height);
ctx.fillStyle = 'red';
ctx.fillRect(this.player.x, this.player.y, this.player.width, this.player.height);
ctx.fillStyle = 'green';
for(var i = 0; i < this.platforms.length; i++) {
var platform = this.platforms[i];
ctx.fillRect(platform.x, platform.y, platform.width, platform.height);
}
},
update: function() {
// player movement
if(this.player.x + this.player.width < this.width) {
this.player.x += this.player.speed;
}
}
};
function gameLoop() {
game.update();
game.draw();
requestAnimationFrame(gameLoop);
}
gameLoop();
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lnRW 著作权归作者所有。请勿转载和采集!