Simple HTML Platformer: Build Your Own Game with HTML, CSS, and JavaScript
Simple HTML Platformer
To create a simple HTML platformer, we will need to use HTML, CSS, and JavaScript.
HTML
First, let's create the basic structure of our platformer using HTML. We will need a canvas element to draw our game on, as well as some buttons to control the player.
<!DOCTYPE html>
<html>
<head>
<title>Simple HTML Platformer</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id='canvas' width='400' height='300'></canvas>
<br>
<button id='left'>Left</button>
<button id='right'>Right</button>
<button id='jump'>Jump</button>
</body>
</html>
CSS
Next, let's style our buttons to make them look nice.
button {
font-size: 20px;
padding: 10px 20px;
margin: 10px;
border-radius: 5px;
background-color: #4CAF50;
color: white;
border: none;
}
JavaScript
Finally, let's write some JavaScript to make our platformer work. We will need to create a player object, handle player movement, and handle collisions with the game world.
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const player = {
x: 50,
y: 50,
width: 20,
height: 20,
speed: 5,
jumping: false,
jumpHeight: 100,
jumpCount: 0
};
function drawPlayer() {
ctx.fillRect(player.x, player.y, player.width, player.height);
}
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function movePlayer() {
if (leftPressed && player.x > 0) {
player.x -= player.speed;
}
if (rightPressed && player.x < canvas.width - player.width) {
player.x += player.speed;
}
if (jumpPressed && !player.jumping) {
player.jumping = true;
}
if (player.jumping) {
player.y -= 5;
player.jumpCount += 5;
if (player.jumpCount > player.jumpHeight) {
player.jumping = false;
player.jumpCount = 0;
}
} else if (player.y < canvas.height - player.height) {
player.y += 5;
}
}
function detectCollisions() {
if (player.y >= canvas.height - player.height) {
player.y = canvas.height - player.height;
player.jumping = false;
player.jumpCount = 0;
}
}
let leftPressed = false;
let rightPressed = false;
let jumpPressed = false;
document.addEventListener('keydown', event => {
if (event.code === 'ArrowLeft') {
leftPressed = true;
} else if (event.code === 'ArrowRight') {
rightPressed = true;
} else if (event.code === 'Space') {
jumpPressed = true;
}
});
document.addEventListener('keyup', event => {
if (event.code === 'ArrowLeft') {
leftPressed = false;
} else if (event.code === 'ArrowRight') {
rightPressed = false;
} else if (event.code === 'Space') {
jumpPressed = false;
}
});
function update() {
clearCanvas();
drawPlayer();
movePlayer();
detectCollisions();
requestAnimationFrame(update);
}
update();
Conclusion
And there you have it! A simple HTML platformer using HTML, CSS, and JavaScript. Feel free to customize it and make it your own. Happy coding!
原文地址: https://www.cveoy.top/t/topic/lmmx 著作权归作者所有。请勿转载和采集!