HTML Platformer Game Code Example - Learn to Create Your Own
<!DOCTYPE html>
<html>
<head>
<title>Platformer</title>
<style>
body {
margin: 0;
}
canvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id='gameCanvas'></canvas>
<script>
// Get canvas element
let canvas = document.getElementById('gameCanvas');
// Get drawing context
let ctx = canvas.getContext('2d');
<pre><code> // Create a new player
let player = {
x: canvas.width/2,
y: canvas.height - 30,
width: 30,
height: 30,
color: 'red',
speed: 5
};
// Create an array of platforms
let platforms = [];
platforms.push({
x: 0,
y: 250,
width: 100,
height: 10
});
platforms.push({
x: 150,
y: 100,
width: 100,
height: 10
});
platforms.push({
x: 300,
y: 300,
width: 100,
height: 10
});
platforms.push({
x: 450,
y: 150,
width: 100,
height: 10
});
// Draw player
function drawPlayer() {
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.width, player.height);
}
// Draw platforms
function drawPlatforms() {
ctx.fillStyle = 'grey';
for(let i = 0; i < platforms.length; i++) {
ctx.fillRect(platforms[i].x, platforms[i].y, platforms[i].width, platforms[i].height);
}
}
// Update player position
function updatePosition() {
player.y += player.speed;
}
// Check collision
function checkCollision() {
for(let i = 0; i < platforms.length; i++) {
let p = platforms[i];
if(player.x + player.width > p.x && player.x < p.x + p.width &&
player.y + player.height > p.y && player.y < p.y + p.height)
{
player.y = p.y - player.height;
}
}
}
// Update game
function update() {
updatePosition();
checkCollision();
}
// Draw game
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPlatforms();
drawPlayer();
}
// Main loop
function loop() {
update();
draw();
requestAnimationFrame(loop);
}
// Run game
loop();
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lnR3 著作权归作者所有。请勿转载和采集!