canvas 实现飞碟射击游戏

var canvas = document.getElementById('canvas');
var cxt = canvas.getContext('2d');

// 射击角度
var ang = 0;
// 子弹
var bullets = [];
// 飞碟
var fly = {'x':100, 'y':100};
// 得分
var score = 0;

// 清除画布
function erase() {
cxt.clearRect(0, 0, canvas.width, canvas.height)
}

// 画炮台
function draw() {
cxt.save();
cxt.beginPath();
cxt.translate(300, 400);
cxt.arc(0, 0, 100, 0, -180*Math.PI/180, true);
cxt.stroke();
cxt.closePath();
cxt.restore();

cxt.save();
cxt.translate(300, 400);
cxt.rotate(ang);
cxt.fillRect(-10, -100, 20, 80);
cxt.restore();
}

// 画飞碟
function drawFly(){
cxt.save();
cxt.fillStyle = 'red';
cxt.beginPath();
cxt.arc(fly.x, fly.y, 10, 0, 360*Math.PI/180, true);
cxt.fill();
cxt.closePath();
cxt.restore();
}

// 画子弹
function drawBullet(){
for(var i=0; i<bullets.length; i++){
cxt.save();
cxt.translate(300, 400);
cxt.rotate(bullets[i].ang);
cxt.fillStyle = 'grey';
cxt.beginPath();
cxt.arc(bullets[i].x, bullets[i].y, 10, 0, 360*Math.PI/180, true);
cxt.fill();
cxt.closePath();
cxt.restore();
}
}

// 随机飞碟
function randomBullet(){
var x = Math.round(Math.random()*580) + 10;
var y = Math.round(Math.random()*190) + 10;
fly.x = x;
fly.y = y;
}

// 子弹运行
function step(){
var _bullets = [];
for(var i=0; i<bullets.length; i++){

var x = 300 - Math.sin(bullets[i].ang)*bullets[i].y;
var y = 400 - Math.abs(Math.cos(bullets[i].ang)*bullets[i].y);

if(Math.sqrt((fly.x-x)*(fly.x-x)+(fly.y-y)*(fly.y-y)) < 20){
score ++;
randomBullet();
}

bullets[i].y -= 5;
if(bullets[i].y > -500 && bullets[i].x > -300 && bullets[i].x < 300){
_bullets.push(bullets[i]);
}
}
bullets = _bullets;
}

// 画得分
function drawScore() {
cxt.save();
cxt.font="20px Verdana";
cxt.fillStyle = 'skyblue';
cxt.fillText('得分:' + score, 500, 50);
cxt.restore();
}

// 鼠标移动控制炮台
canvas.onmousemove = function(e){
var ev = e || window.event;
var _x = ev.clientX - canvas.offsetLeft;
var _y = ev.clientY - canvas.offsetTop;
if(Math.sqrt((_x-300)*(_x-300)+(_y-400)*(_y-400)) <=100){
ang = Math.atan((_x - 300)/(400 - _y));
}
};

// 单击鼠标进行射击
var lastTime = 0;
canvas.onclick = function(){
var nowDate = new Date();
if(nowDate.getTime() - lastTime < 200){
return;
}
lastTime = nowDate.getTime();
var bullet = {'x':0,'y':-110,'ang':ang};
bullets.push(bullet);
};

function animate() {
erase();
draw();
drawFly();
drawBullet();
step();
drawScore();
timer = requestAnimationFrame(animate);
}

animate();

原文地址:https://www.cnblogs.com/liubu/p/7846968.html