Build Your Own Platform Game: HTML & JavaScript Tutorial
<!DOCTYPE html>
<html>
<head>
<title>Platformer Game</title>
<style type='text/css'>
#player {
position: absolute;
width: 48px;
height: 48px;
background-image: url('player.png');
}
#floor {
position: absolute;
width: 100%;
height: 30px;
background-color: #009900;
bottom: 0;
}
</style>
</head>
<body>
<div id='player'></div>
<div id='floor'></div>
<pre><code><script type='text/javascript'>
// variables
var player = document.getElementById('player');
var floor = document.getElementById('floor');
var gravity = 0.2;
var jumpForce = 4; // the amount of force applied to a jump
var xVelocity = 0;
var yVelocity = 0;
// game loop
setInterval(update, 16); // 60 fps
// update function
function update() {
// apply gravity to the velocity
yVelocity += gravity;
// update the player's position
player.style.top = player.offsetTop + yVelocity + 'px';
player.style.left = player.offsetLeft + xVelocity + 'px';
// if the player is touching the floor, reset yVelocity
if (player.offsetTop + player.offsetHeight >= floor.offsetTop) {
yVelocity = 0;
}
// jump when the spacebar is pressed
if (event.keyCode === 32) {
yVelocity -= jumpForce;
}
}
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lnRF 著作权归作者所有。请勿转载和采集!