HTML Platform Game: Create a Simple Platformer with JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Platformer Game</title>
</head>
<body>
<div id='game'>
<canvas id='gameCanvas' width='800' height='600'></canvas>
</div>
<script>
// create canvas element
var canvas = document.getElementById('gameCanvas');
var ctx = canvas.getContext('2d');
// set canvas size
ctx.canvas.width = 800;
ctx.canvas.height = 600;
// create a platform
var platform = {
x: 0,
y: 500,
width: 800,
height: 100
};
// draw the platform
ctx.fillStyle = '#000000';
ctx.fillRect(platform.x, platform.y, platform.width, platform.height);
// create a character
var character = {
x: 0,
y: 0,
width: 50,
height: 50,
speed: 5
};
// draw character
ctx.fillStyle = '#0000FF';
ctx.fillRect(character.x, character.y, character.width, character.height);
// move character
document.onkeydown = function(e) {
switch (e.keyCode) {
case 37: // left arrow
character.x -= character.speed;
break;
case 38: // up arrow
character.y -= character.speed;
break;
case 39: // right arrow
character.x += character.speed;
break;
case 40: // down arrow
character.y += character.speed;
break;
}
// check for collision with platform
if (character.y + character.height >= platform.y &&
character.x + character.width >= platform.x &&
character.x <= platform.x + platform.width) {
character.y = platform.y - character.height;
}
// clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw platform
ctx.fillStyle = '#000000';
ctx.fillRect(platform.x, platform.y, platform.width, platform.height);
// draw character
ctx.fillStyle = '#0000FF';
ctx.fillRect(character.x, character.y, character.width, character.height);
}
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lnRZ 著作权归作者所有。请勿转载和采集!