考虑到我有2个方格,我知道x和y位置,我也知道大小,如果我想看看物体是否相互碰撞,那么使用的公式是什么。
if( ((shapeA->getX() - shapeA->getSize()) > (player->getX() - player->getSize())
&& (shapeA->getX() + shapeA->getSize()) < (player->getX() + player->getSize()))
&& (shapeA->getY() - shapeA->getSize() > player->getY() - player->getSize()
&& (shapeA->getY() + shapeA->getSize()) < (player->getY() + player->getSize()))
)
这很有效,但它很奇怪(并不是所有时间)。我一定错过了什么
答案 0 :(得分:4)
检查矩形是否与另一个矩形相交或接触是非常容易的。看看下面的图片:
如您所见,如果([x,x + a]和[X,X + A])和([y,y + b]和[Y,Y + B])之间的交点,则两个矩形相交两者都不是空的。
struct Rectangle{
bool intersects(const Rectangle&);
unsigned int a; //!< width of the rectangle
unsigned int b; //!< height of the rectangle
unsigned int x; //!< x position
unsigned int y; //!< y position
};
bool Rectangle::intersects(const Rectangle& oRectangle){
return (x < oRectangle.x + oRectangle.a) && // [x,x+a], [X,X+A] intersection
(oRectangle.x < x + a) && // [x,x+a], [X,X+A] intersection
(y < oRectangle.y + oRectangle.b) && // [y,y+b], [Y,Y+B] intersection
(oRectangle.y < y + b); // [y,y+b], [Y,Y+B] intersection
}
所以你的代码应该是
if(((shapeA->getX() + shapeA->getSize()) > (player->getX()) // x intersection
&& (shapeA->getX() < (player->getX() + player->getSize())) // x intersection
&& (shapeA->getY() < player->getY() + player->getSize() // y intersection
&& (shapeA->getY() + shapeA->getSize()) > player->getY()) // y intersection
)
答案 1 :(得分:2)
假设getX / Y给出方块的左下角,
shapeMinX = shapeA; shapeMaxX = shapeB;
if (shapeA()->getX() > shapeB()->getX())
swap (shapeMinX, shapeMaxX);
shapeMinY = shapeA; shapeMaxY = shapeB;
if (shapeA()->getY() > shapeB()->getY())
swap (shapeMinY, shapeMaxY);
collision = (shapeMinX->getX()+shapeMinX->size() >= shapeMaxX()->getX) || (shapeMinX->getY()+shapeMinY->size() >= shapeMaxY()->getY);
答案 2 :(得分:2)
你做错了测试,试试这个:
int left_bound_A= shapeA->getX()-shapeA->getSize();
int right_bound_A= shapeA->getX()+shapeA->getSize();
int top_bound_A= shapeA->getY()-shapeA->getSize();
int bottom_bound_A= shapeA->getY()+shapeA->getSize();
int left_bound_B= shapeB->getX()-shapeB->getSize();
int right_bound_B= shapeB->getX()+shapeB->getSize();
int top_bound_B= shapeB->getY()-shapeB->getSize();
int bottom_bound_B= shapeB->getY()+shapeB->getSize();
if( left_bound_A < right_bound_B &&
right_bound_A > left_bound_B &&
top_bound_A > bottom_bound_B &&
bottom_bound_A < top_bound_B ) colide(shapeA,shapeB);
一般方法是测试形状交叉。如果实现Box或Rectangle类,代码将简化为:
Box colision= intersect( shapeA->getBoundBox(), shapeB->getBoundBox() );
if( colision.have_positive_area() )
colide(shapeA,shapeB,colision);
答案 3 :(得分:0)
是的,检查两个矩形是否简单的方法。 正如一个建议,如果你想要计算矩形列表中矩形之间的所有可能的交集,通过增加它们的边界的x来预先排序它们然后开始利用这种关系的比较。这个问题可能会有所帮助
可能会感兴趣