Simple HTML5 Platformer Game - Code Example
<!DOCTYPE html>
<html>
<head>
<title>Simple HTML5 Platformer Game</title>
<style>
body {
margin: 0;
padding: 0;
}
canvas {
background-color: #EEE;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id='game'></canvas>
<script>
var canvas = document.getElementById('game');
var ctx = canvas.getContext('2d');
<pre><code> // Global Variables
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 5;
var dy = -5;
var ballRadius = 10;
// Draw Ball
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = '#0095DD';
ctx.fill();
ctx.closePath();
}
// Draw Platform
function drawPlatform() {
ctx.beginPath();
ctx.rect(0, canvas.height-20, canvas.width, 20);
ctx.fillStyle = '#0095DD';
ctx.fill();
ctx.closePath();
}
// Draw
function draw() {
// Clear Canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw Ball and Platform
drawBall();
drawPlatform();
// Move Ball
x += dx;
y += dy;
// Bounce Ball off Walls
if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
dy = -dy;
}
// Bounce Ball off Platform
if(y + dy > canvas.height-ballRadius-20 && x > 0 && x < canvas.width) {
dy = -dy;
}
// Request next animation frame
requestAnimationFrame(draw);
}
requestAnimationFrame(draw);
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lnRM 著作权归作者所有。请勿转载和采集!