Simple HTML Platformer Game: Create Your First Jump and Run Game
<html>
<head>
<title>Simple HTML Platformer Game</title>
</head>
<body>
<canvas id='canvas' width='400' height='400'></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 0;
var y = 0;
var width = 20;
var height = 20;
var speed = 5;
var isJumping = false;
var jumpSpeed = 10;
var gravity = 1;
var platformX = 0;
var platformY = 200;
var platformWidth = 400;
var platformHeight = 10;
<pre><code> function update() {
// move the character
x += speed;
// check if character is jumping
if (isJumping) {
// apply gravity
y -= jumpSpeed;
jumpSpeed -= gravity;
}
// check if character is on the platform
if (y > platformY && (x > platformX && x < platformX + platformWidth)) {
y = platformY;
isJumping = false;
}
// draw the character
ctx.fillStyle = 'red';
ctx.fillRect(x, y, width, height);
// draw the platform
ctx.fillStyle = 'green';
ctx.fillRect(platformX, platformY, platformWidth, platformHeight);
// loop
requestAnimationFrame(update);
}
document.body.addEventListener('keydown', function(e) {
if (e.keyCode == 32) {
isJumping = true;
jumpSpeed = 10;
}
});
update();
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmmj 著作权归作者所有。请勿转载和采集!