HTML Platform Game Code Example - Learn to Build a Basic Platformer
<html>
<head>
<title>Platformer</title>
<style>
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<pre><code><script>
// Get the canvas element
var canvas = document.getElementById('myCanvas');
// Get the context element which is used to draw on the canvas
var ctx = canvas.getContext('2d');
// Set the position of the player
var x = canvas.width / 2;
var y = canvas.height - 30;
// Set the size of the player
var playerWidth = 20;
var playerHeight = 20;
// Set the speed of the player
var speedX = 2;
var speedY = -2;
// Set the position of the obstacles
var obstacleX = canvas.width / 2;
var obstacleY = canvas.height - 30;
// Set the size of the obstacle
var obstacleWidth = 20;
var obstacleHeight = 20;
// Draw the player
function drawPlayer() {
ctx.beginPath();
ctx.rect(x, y, playerWidth, playerHeight);
ctx.fillStyle = '#0095DD';
ctx.fill();
ctx.closePath();
}
// Draw the obstacle
function drawObstacle() {
ctx.beginPath();
ctx.rect(obstacleX, obstacleY, obstacleWidth, obstacleHeight);
ctx.fillStyle = '#0095DD';
ctx.fill();
ctx.closePath();
}
// Move the player and the obstacle
function movePlayer() {
x += speedX;
y += speedY;
obstacleX -= speedX;
obstacleY -= speedY;
if (x + playerWidth > canvas.width || x < 0) {
speedX = -speedX;
}
if (y + playerHeight > canvas.height || y < 0) {
speedY = -speedY;
}
if (obstacleX + obstacleWidth > canvas.width || obstacleX < 0) {
speedX = -speedX;
}
if (obstacleY + obstacleHeight > canvas.height || obstacleY < 0) {
speedY = -speedY;
}
}
// Check for player collisions with the obstacle
function checkCollision() {
if (x < obstacleX + obstacleWidth &&
x + playerWidth > obstacleX &&
y < obstacleY + obstacleHeight &&
y + playerHeight > obstacleY) {
alert('Game Over!');
document.location.reload();
}
}
// Draw everything
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPlayer();
drawObstacle();
movePlayer();
checkCollision();
requestAnimationFrame(draw);
}
draw();
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lnRU 著作权归作者所有。请勿转载和采集!