javascript - 碰撞检测函数始终返回 true

标签 javascript collision-detection

我可能错过了一些非常简单的东西,但我不明白为什么这个函数总是返回 true 并记录两个对象,即使它们彼此不靠近。 我的代码:

var collideRect=function(obj1, obj2){
   var x1=obj1.x,y1=obj1.y,x2=obj2.x, y2=obj2.y;
   var b1=obj1.breadth,h1=obj1.height;
   var b2=obj2.breadth,h2=obj2.height;
   var xCollide, yCollide;
// determine if the x values are closer than half the breadth of each rectangle to each other
   if(x1+b1/2>x2-b2/2||x1-b1/2<x2+b2/2){xCollide=true};
// determine if the y values are closer than half their heights from one another 
   if(y1+h1/2>y2-h2/2||y1-h1/2<y2+h2/2){yCollide=true};
   if(xCollide&&yCollide){
    console.log(JSON.stringify(obj1)+".   "+JSON.stringify(obj2)) ;
    return true;
   }; 
}

没有一个值是ever0。该函数接受每个具有属性的对象: 宽度, 高度, X, y。 这些都是正数。我检查了每个语句的操作顺序,都没有问题。

最佳答案

您的 if 语句不正确。请参阅下面的调整算法和基本控制台断言。

本质上,您需要检测任何边缘之间是否没有空间。如果没有空间,您就知道发生了碰撞。

分割如下:

第 1 步。

检查矩形1的左边缘。

如果矩形1的左边缘小于矩形2的右边缘(x2+b2),则矩形1的左侧和矩形2的右侧可能有交集。

第二步。

检查矩形1的右侧。

如果矩形1的右侧大于矩形2的左侧,则矩形1与矩形2在矩形2的左侧相交。我们使用 && 检测这两个条件是否成立,以确保发生了冲突。

我们对两个矩形的 y 坐标进行完全相同的检查,以实现检测矩形是否在 y 平面上相交。

var collideRect = function (obj1, obj2) {
	var collision = false;

	var x1 = obj1.x,
	y1 = obj1.y,
	x2 = obj2.x,
	y2 = obj2.y;

	var b1 = obj1.breadth,
	h1 = obj1.height;

	var b2 = obj2.breadth,
	h2 = obj2.height;

	var xCollide,
	yCollide;
        // if left edge of rect1 is left of the left edge of rect2 plus its 
        // width AND left edge of rect1 plus rect1's width is greater than 
        // the left edge of rect2, we have an x-coordinate collision.
        // if either set of conditions is false, the rects don't overlap.
	if (x1 < x2 + b2 && x1 + b1 > x2) {
		xCollide = true;
	}
    // same as the x check but on the y plane
	if (y1 < y2 + h2 && h1 + y1 > y2) {
		yCollide = true;
	}

	if (xCollide && yCollide) {
		console.log(JSON.stringify(obj1) + ".   " + JSON.stringify(obj2));
		collision = true;
	}
	return collision;
}

// test
var rect1 = {
	x: 5,
	y: 5,
	breadth: 50,
	height: 50
};
var rect2 = {
	x: 20,
	y: 10,
	breadth: 10,
	height: 10
};

console.assert(collideRect(rect1, rect2) === true); // collision

var rect3 = {
	x: 55,
	y: 55,
	breadth: 50,
	height: 50
};
var rect4 = {
	x: 20,
	y: 10,
	breadth: 10,
	height: 10
};

console.assert(collideRect(rect3, rect4) === false); // no collision

关于javascript - 碰撞检测函数始终返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46071711/

相关文章:

algorithm - GJK 算法中的支持函数

unity-game-engine - 如何检测 Unity 中潜在的碰撞?

javascript - 数组碰撞检测中的 p5.js 对象

javascript - 在按钮 id 提交之前需要检查 4 个复选框才能运行 js

javascript - 如何停止在页面重新加载时从 jQuery 函数中删除附加类

javascript - 将对象内的两个属性相乘

javascript - 如何从 Javascript 设置 WebSocket Origin Header?

python - Pygame Collidepoint 函数未按预期工作

Javascript 正确碰撞后重置函数

javascript - 公共(public) Github 页面站点上的 Github API 速率限制