盒子碰撞代码
我的盒子碰撞代码不起作用。
bool checkCollide(int x, int y, int oWidth, int oHeight, int xTwo, int yTwo, int oTwoWidth, int oTwoHeight)
{
if (xTwo + oTwoWidth < x)
return false; // box 2 is left of box 1
if (x + oWidth < xTwo)
return false; // box 1 is left of box 2
if (xTwo > x + oWidth)
return false; // box 2 is right of box 1
if (x > xTwo + oTwoWidth)
return false; // box 1 is right of box 2
if (yTwo + oTwoHeight < y)
return false; // box 2 is up of box 1
if (y + oHeight < yTwo)
return false; // box 1 is up of box 2
if (yTwo > y + oHeight)
return false; // box 2 is down of box 1
if (y > yTwo + oTwoHeight)
return false; // box 1 is down of box 2
return true;
}
我的一个盒子显然正在超越另一个盒子,但是什么也没有发生。 由于某种原因,它似乎返回 false。我正在检查一个“矩形”是否超出了另一个“矩形”的范围,如果不是则返回 true。为什么它不起作用?
My box collision code is not working.
bool checkCollide(int x, int y, int oWidth, int oHeight, int xTwo, int yTwo, int oTwoWidth, int oTwoHeight)
{
if (xTwo + oTwoWidth < x)
return false; // box 2 is left of box 1
if (x + oWidth < xTwo)
return false; // box 1 is left of box 2
if (xTwo > x + oWidth)
return false; // box 2 is right of box 1
if (x > xTwo + oTwoWidth)
return false; // box 1 is right of box 2
if (yTwo + oTwoHeight < y)
return false; // box 2 is up of box 1
if (y + oHeight < yTwo)
return false; // box 1 is up of box 2
if (yTwo > y + oHeight)
return false; // box 2 is down of box 1
if (y > yTwo + oTwoHeight)
return false; // box 1 is down of box 2
return true;
}
On of my boxes is clearly going over the other, however nothing is happening.
It seems to be returning false for some reason. I'm checking if one "rectangle" is out of bounds of the other, and if it isn't return true. Why isn't it working?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是我的做法(我会提供一个 AABB 对象而不是槽)。
实际上,您可以直接用值替换 x1Max 等,而不是使用临时变量。我添加它们是为了便于阅读。
请注意,此功能仅适用于 2D 盒子,但只需要多一条带有 z 轴的测试线即可实现 3D 兼容。
----------
现在让我们看看您的代码以及一些注释
正如您所看到的,一半的测试是不需要的。
考虑到 X 轴,您的第一个测试与第四个相同;你的第二次测试与第三次测试相同。
----------
但是,当框重叠时,我找不到您的函数不返回 true 的任何原因。它应该有效。
我使用以下值进行了测试
,它返回 false,并按预期返回 true。
Here is how I would have done it (I would have provided an AABB object instead trough)
Indeed you can replace the x1Max etc directly with the values instead of using temporary variables. I added them for readability.
Note that this function does work with 2D boxes only, but it only require one more test line with z axis to be 3D compatible.
----------
Now let see your code with some comments on it
So as you can see, half the tests are not required.
Considering the X axis, you first test is the same as the fourth one; your second test is the same as the third one.
----------
However, I can't spot any reason why your function does not return true when the box are overlapping. It should work.
I tested with the following values
And it return false, and true as expected.