HTML Platformer Game: Code Example & Tutorial
<html>
<head>
<title>Platformer Game</title>
<style>
#player {
position: relative;
width: 50px;
height: 50px;
background-color: #e74c3c;
}
#platform {
position: relative;
width: 300px;
height: 30px;
background-color: #2ecc71;
}
</style>
</head>
<body>
<div id='player'></div>
<div id='platform'></div>
<script>
// get player and platform elements
let player = document.getElementById('player');
let platform = document.getElementById('platform');
<pre><code>// set initial player position
let posX = 0;
let posY = 0;
// handle movement
document.addEventListener('keydown', function(e) {
if (e.keyCode === 37) {
posX -= 5;
} else if (e.keyCode === 38) {
posY -= 5;
} else if (e.keyCode === 39) {
posX += 5;
} else if (e.keyCode === 40) {
posY += 5;
}
// set updated player position
player.style.left = posX + 'px';
player.style.top = posY + 'px';
// check for collision
let playerRect = player.getBoundingClientRect();
let platformRect = platform.getBoundingClientRect();
if (playerRect.right > platformRect.left &&
playerRect.left < platformRect.right &&
playerRect.bottom > platformRect.top &&
playerRect.top < platformRect.bottom) {
alert('Collision!');
}
});
</code></pre>
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lnRY 著作权归作者所有。请勿转载和采集!