const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); // 定义目标对象 class Target { constructor(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; } draw() { ctx.fillStyle = 'blue'; ctx.fillRect(this.x, this.y, this.width, this.height); } } // 定义子弹对象 class Bullet { constructor(x, y, speed) { this.x = x; this.y = y; this.speed = speed; this.radius = 5; this.targetX = x; // 目标位置 this.targetY = y; } draw() { ctx.fillStyle = 'red'; ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2); ctx.fill(); ctx.closePath(); } update() { // 计算方向 const dx = this.targetX - this.x; const dy = this.targetY - this.y; const dist = Math.sqrt(dx * dx + dy * dy); if (dist > this.speed) { this.x += dx / dist * this.speed; this.y += dy / dist * this.speed; } else { this.x = this.targetX; this.y = this.targetY; } } } // 创建目标和子弹 const target = new Target(400, 100, 50, 50); const bullets = []; // 发射子弹 function shootBullet() { bullets.push(new Bullet(canvas.width / 2, canvas.height - 10, 5)); } // 游戏循环 function gameLoop() { ctx.clearRect(0, 0, canvas.width, canvas.height); target.draw(); bullets.forEach(bullet => { bullet.update(); bullet.draw(); }); requestAnimationFrame(gameLoop); } // 添加键盘事件监听器 document.addEventListener('keydown', function(event) { if (event.code === 'Space') { shootBullet(); } }); // 启动游戏循环 gameLoop();