Create Your Own Platformer Game with HTML, CSS, and JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Platformer Game</title>
<style>
body {
background-color: #cccccc;
}
<pre><code> #game-container {
position: relative;
width: 900px;
height: 500px;
}
#player {
position: absolute;
width: 20px;
height: 20px;
background-color: #000000;
}
.platform {
position: absolute;
width: 100px;
height: 10px;
background-color: #333333;
}
</style>
</head>
<body>
<div id='game-container'>
<div id='player'></div>
<div class='platform' style='left: 50px; top: 50px;'></div>
<div class='platform' style='left: 200px; top: 350px;'></div>
<div class='platform' style='left: 500px; top: 200px;'></div>
</div>
<script>
// Player object
var player = {
x: 0,
y: 0,
speed: 5
};
// Platform object
var platforms = [
{
x: 50,
y: 50,
width: 100,
height: 10
},
{
x: 200,
y: 350,
width: 100,
height: 10
},
{
x: 500,
y: 200,
width: 100,
height: 10
}
];
// Update position of player
function updatePlayerPosition() {
player.x += player.speed;
document.getElementById('player').style.left = player.x + 'px';
document.getElementById('player').style.top = player.y + 'px';
}
// Check for collision between player and platform
function checkCollision() {
for (var i = 0; i < platforms.length; i++) {
if (player.x + 20 >= platforms[i].x &&
player.x <= platforms[i].x + platforms[i].width &&
player.y + 20 >= platforms[i].y &&
player.y <= platforms[i].y + platforms[i].height) {
player.y = platforms[i].y - 20;
}
}
}
// Game loop
function gameLoop() {
updatePlayerPosition();
checkCollision();
setTimeout(gameLoop, 1000 / 60);
}
gameLoop();
</script>
</body>
</code></pre>
</html>
原文地址: https://www.cveoy.top/t/topic/lnRL 著作权归作者所有。请勿转载和采集!