HTML Platformer Game Code: Simple Example
<!DOCTYPE html>
<html>
<head>
<title>Platformer Game</title>
<style>
/*Styles for the game*/
body {
background-color: black;
margin: 0;
padding: 0;
}
<pre><code> #game-container {
margin: 0 auto;
width: 800px;
height: 600px;
background-color: white;
position: relative;
}
#player {
width: 20px;
height: 20px;
position: absolute;
background-color: blue;
top: 0;
left: 0;
}
#platforms {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.platform {
background-color: gray;
width: 50px;
height: 10px;
position: absolute;
}
</style>
</head>
<body>
<div id='game-container'>
<div id='player'></div>
<div id='platforms'>
<div class='platform' style='top: 50px; left: 50px;'></div>
<div class='platform' style='top: 100px; left: 200px;'></div>
<div class='platform' style='top: 250px; left: 250px;'></div>
<div class='platform' style='top: 350px; left: 400px;'></div>
</div>
</div>
<script>
//Script to control the player
let player = document.querySelector('#player');
//Add event listeners for key presses
document.addEventListener('keydown', function(e) {
//Move left
if (e.keyCode === 37) {
player.style.left = (player.offsetLeft - 10) + 'px';
}
//Move right
else if (e.keyCode === 39) {
player.style.left = (player.offsetLeft + 10) + 'px';
}
});
</script>
</body>
</code></pre>
</html>
原文地址: https://www.cveoy.top/t/topic/lnR1 著作权归作者所有。请勿转载和采集!