HTML Platform Game Code: Create a Simple Platformer
<!DOCTYPE html>
<html>
<head>
<title>Platformer</title>
<style>
body {
text-align: center;
}
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id='myCanvas' width='400' height='400'></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#FF0000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
<pre><code>// Player
var x = canvas.width / 2;
var y = canvas.height - 30;
var dx = 2;
var dy = -2;
var ballRadius = 10;
// Platforms
var platformWidth = 75;
var platformHeight = 10;
var platformX = (canvas.width - platformWidth) / 2;
var platformY = (canvas.height - platformHeight);
// Draw Player
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = '#0095DD';
ctx.fill();
ctx.closePath();
}
// Draw Platforms
function drawPlatform() {
ctx.beginPath();
ctx.rect(platformX, platformY, platformWidth, platformHeight);
ctx.fillStyle = '#0095DD';
ctx.fill();
ctx.closePath();
}
// Update ball position
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawPlatform();
x += dx;
y += dy;
}
setInterval(draw, 10);
</code></pre>
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lnRV 著作权归作者所有。请勿转载和采集!