JavaScript Canvas 碰撞检测:方向判断代码示例
您可以使用以下代码来检测两个矩形是否发生碰撞,并分别检测碰撞发生在哪个方向:
function isColliding(rect1, rect2) {
if (rect1.x < rect2.x + rect2.width &&
rect1.x + rect1.width > rect2.x &&
rect1.y < rect2.y + rect2.height &&
rect1.y + rect1.height > rect2.y) {
return true;
}
return false;
}
function getCollisionDirection(rect1, rect2) {
var dx = (rect1.x + rect1.width / 2) - (rect2.x + rect2.width / 2);
var dy = (rect1.y + rect1.height / 2) - (rect2.y + rect2.height / 2);
var width = (rect1.width + rect2.width) / 2;
var height = (rect1.height + rect2.height) / 2;
var crossWidth = width * dy;
var crossHeight = height * dx;
if (Math.abs(dx) <= width && Math.abs(dy) <= height) {
if (crossWidth > crossHeight) {
return (crossWidth > -crossHeight) ? 'bottom' : 'left';
} else {
return (crossWidth > -crossHeight) ? 'right' : 'top';
}
}
return false;
}
// 示例用法
var rect1 = {x: 0, y: 0, width: 50, height: 50};
var rect2 = {x: 60, y: 60, width: 50, height: 50};
if (isColliding(rect1, rect2)) {
console.log('碰撞发生');
var collisionDirection = getCollisionDirection(rect1, rect2);
console.log('碰撞发生在:' + collisionDirection);
} else {
console.log('未发生碰撞');
}
您只需将 rect1 和 rect2 替换为您要检测碰撞的两个矩形对象。如果发生碰撞,isColliding() 函数将返回 true,否则返回 false。getCollisionDirection() 函数将返回碰撞发生的方向,如果未发生碰撞,将返回 false。
原文地址: https://www.cveoy.top/t/topic/pgpf 著作权归作者所有。请勿转载和采集!