对象碰撞检测机制
重要通知
类目简介
基本概况
碰撞检测基础方法 | 缺陷:不适用任意多边形、圆形、图像与精灵之间的碰撞检测:collision
外接图形(矩形、圆)判别法:不严谨。
function ballWillHitLedge() {
var ballRight = ball.left + ball.width,
ballBottom = ball.top + ball.height,
ledgeRight = ledge.left + ledge.width,
nextBallBottomEstimate = ballBottom + ball.velocityY / fps;
return bacllRight > ledge.left && ball.left < ledgeRight && ballBottom < ledge.top && nextBallBottomEstimate > ledge.top;
}
事前碰撞检测法 事后碰撞检测法
外接圆碰撞法
检测两个圆形的圆心之间距离是否小于两圆半径之和。
function isBallInBucket() {
var ballCenter = { x: ball.left + BALL_RADIUS, y: ball.top + BALL_RADIUS },
distance = Math.pow(bucketHitCenter.x - ballCenter.x, 2) + Math.pow(bucketHitCenter.y - ballCenter.y, 2);
return distance < BALL_RADIUS + bucketHitRadius;
}
碰到墙壁即被弹回的小球
function handleEdgeCollisionn() {
var bbox = getBoundingBox(ball),
right = bbox.left + bbox.width,
bottom = bbox.top + bbox.height;
if (right > canvas.width || bbox.left < 0) {
velocityX = -velocityX;
if (right > canvas.width) {
ball.left -= right - canvas.width;
}
if (bbox.left < 0) {
ball.left -= bbox.left;
}
}
if (bottom > canvas.height || bbox.top < 0) {
velocityY = -velocityY;
if (bottom > canvas.height) {
ball.top -= bottom - canvas.height;
}
if (bbox.top < 0) {
ball.top -= bbox.top;
}
}
}
光线投影法:稍微严谨、更精确(相对于外接图形判别法)
分离轴定理 SAT(超平面分离定理):只适用于凸多边形
多边形检测 圆形、图像与精灵之间的碰撞检测。
凹多边形的碰撞检测
圆形与多边形之间的碰撞检测
最小平移向量(MTV)
适用范围:检测二维平面、三维空间中的多边形碰撞检测。 定义:如果要让某个物体不再与另外一个物体相撞,所需移动的最小距离。