js实现碰壁
实现碰壁效果的基本思路
在JavaScript中实现碰壁效果通常涉及检测物体与边界或障碍物的碰撞,并做出相应反应(如反弹、停止等)。以下是几种常见实现方式:
使用Canvas检测边界碰撞
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
let x = 50, y = 50, dx = 2, dy = 2, radius = 20;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.closePath();
// 边界检测
if (x + dx > canvas.width - radius || x + dx < radius) {
dx = -dx;
}
if (y + dy > canvas.height - radius || y + dy < radius) {
dy = -dy;
}
x += dx;
y += dy;
requestAnimationFrame(draw);
}
draw();
使用DOM元素的边界检测
const box = document.getElementById('movingBox');
let posX = 0, posY = 0, speedX = 2, speedY = 2;
function move() {
const maxX = window.innerWidth - box.offsetWidth;
const maxY = window.innerHeight - box.offsetHeight;
posX += speedX;
posY += speedY;
// 碰壁检测
if (posX >= maxX || posX <= 0) {
speedX = -speedX;
}
if (posY >= maxY || posY <= 0) {
speedY = -speedY;
}
box.style.left = posX + 'px';
box.style.top = posY + 'px';
requestAnimationFrame(move);
}
move();
碰撞检测的数学原理
对于矩形碰撞检测,可以使用以下逻辑判断:
rect1.x < rect2.x + rect2.width &&
rect1.x + rect1.width > rect2.x &&
rect1.y < rect2.y + rect2.height &&
rect1.y + rect1.height > rect2.y
对于圆形碰撞检测,使用距离公式:

distance = Math.sqrt((x2 - x1)^2 + (y2 - y1)^2)
if (distance < radius1 + radius2) {
// 发生碰撞
}
优化碰撞检测性能
对于大量物体的碰撞检测,可以采用空间分区技术如:
- 四叉树(QuadTree)
- 网格分区(Grid Partitioning)
- 边界体积层次结构(BVH)
使用物理引擎实现更真实的碰壁
第三方库如Matter.js、Box2D等提供更完善的物理碰撞系统:

// 使用Matter.js示例
const engine = Matter.Engine.create();
const world = engine.world;
// 创建墙壁边界
const wallOptions = { isStatic: true };
Matter.Composite.add(world, [
Matter.Bodies.rectangle(400, 0, 800, 50, wallOptions), // 上墙
Matter.Bodies.rectangle(400, 600, 800, 50, wallOptions), // 下墙
Matter.Bodies.rectangle(0, 300, 50, 600, wallOptions), // 左墙
Matter.Bodies.rectangle(800, 300, 50, 600, wallOptions) // 右墙
]);
// 创建可碰撞物体
const ball = Matter.Bodies.circle(200, 200, 20);
Matter.Composite.add(world, ball);
// 运行引擎
Matter.Engine.run(engine);
碰撞后的物理响应
实现更真实的碰壁效果需要考虑:
- 碰撞角度计算(使用向量反射公式)
- 能量损失(恢复系数)
- 摩擦力影响
- 角动量传递
向量反射公式示例:
[ \mathbf{v}' = \mathbf{v} - 2(\mathbf{v} \cdot \mathbf{n})\mathbf{n} ]
其中v是入射向量,n是法线向量,v'是反射向量。






