Simple HTML Platformer Game - Build Your First Game Now!
<!DOCTYPE html>
<html>
<body>
<canvas id='canvas' width='500' height='370' style='border:1px solid #000000;'></canvas>
<script>
// canvas variables
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var ballRadius = 10;
<pre><code> // platform variables
var platformHeight = 10;
var platformWidth = 75;
var platformX = (canvas.width - platformWidth)/2;
// draw the ball
function drawBall(){
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = '#0095DD';
ctx.fill();
ctx.closePath();
}
// draw the platform
function drawPlatform(){
ctx.beginPath();
ctx.rect(platformX, canvas.height-platformHeight, platformWidth, platformHeight);
ctx.fillStyle = '#0095DD';
ctx.fill();
ctx.closePath();
}
// draw function
function draw(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawPlatform();
x += dx;
y += dy;
// check for wall collisions
if(x + dx > canvas.width-ballRadius || x + dx < ballRadius){
dx = -dx;
}
// check for platform collisions
if(y + dy < ballRadius) {
dy = -dy;
} else if (y + dy > canvas.height-ballRadius) {
// check if the ball is hitting the platform
if(x > platformX && x < platformX + platformWidth){
dy = -dy;
}
else {
alert('GAME OVER');
document.location.reload();
}
}
}
// call draw function every 10ms
setInterval(draw, 10);
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmmy 著作权归作者所有。请勿转载和采集!