“JS大球吃小球”通常指的是使用JavaScript编写的一种游戏逻辑,其中一个较大的球(通常称为“大球”)可以“吃掉”一个或多个较小的球(称为“小球”)。这种游戏逻辑常见于各种在线小游戏或教育项目中,用于演示基本的物理碰撞检测、对象运动和交互等概念。
以下是一个简单的2D“大球吃小球”游戏的JavaScript代码示例:
// 获取画布和上下文
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// 定义大球和小球
let bigBall = { x: 100, y: 100, radius: 20, dx: 2, dy: 2 };
let smallBalls = [
{ x: 50, y: 50, radius: 10 },
{ x: 150, y: 150, radius: 10 },
// ... 可以添加更多小球
];
// 绘制球
function drawBall(ball) {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
ctx.fill();
}
// 更新球的位置
function updateBall(ball) {
ball.x += ball.dx;
ball.y += ball.dy;
// 边界检测
if (ball.x + ball.radius > canvas.width || ball.x - ball.radius < 0) {
ball.dx = -ball.dx;
}
if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0) {
ball.dy = -ball.dy;
}
}
// 碰撞检测
function checkCollision() {
smallBalls.forEach((smallBall, index) => {
let dx = bigBall.x - smallBall.x;
let dy = bigBall.y - smallBall.y;
let distance = Math.sqrt(dx * dx + dy * dy);
if (distance < bigBall.radius + smallBall.radius) {
// 碰撞发生,移除小球
smallBalls.splice(index, 1);
}
});
}
// 游戏循环
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall(bigBall);
smallBalls.forEach(drawBall);
updateBall(bigBall);
checkCollision();
requestAnimationFrame(gameLoop);
}
// 开始游戏
gameLoop();
dx
和dy
的值来实现。没有搜到相关的沙龙