我有一个简单的设置,它有一个球在屏幕周围弹跳,我希望能够给出它不能在里面移动的物体(它们将充当障碍物)。目前有以下逻辑尝试实现此目的。
void AnimatableObject::ExcludeRects(AnimatableObject *obj) {
for (int i = 0; i < obj->numberOfExclusionBounds; i++) {
SDL_Rect bounds = obj->exclusionBounds[i];
/* TOUCHING SIDES OF THE RECT*/
bool touchingTopOfRect = obj->m_dY + obj->m_dHeight > bounds.y &&
obj->m_dY < bounds.y + bounds.h &&
obj->m_dX > bounds.x &&
obj->m_dX + obj->m_dWidth < bounds.x + bounds.w;
bool touchingBottomOfRect = obj->m_dY < bounds.y + bounds.h &&
obj->m_dY > bounds.y &&
obj->m_dX > bounds.x &&
obj->m_dX + obj->m_dWidth < bounds.x + bounds.w;
bool touchingRightOfRect = obj->m_dX < bounds.x + bounds.w &&
obj->m_dX > bounds.x &&
obj->m_dY > bounds.y &&
obj->m_dY + obj->m_dHeight < bounds.y + bounds.h;
bool touchingLeftOfRect = obj->m_dX + obj->m_dWidth > bounds.x &&
obj->m_dX + obj->m_dWidth < bounds.x + bounds.w &&
obj->m_dY > bounds.y &&
obj->m_dY + obj->m_dHeight > bounds.y + bounds.h;
// Top of a rect.
if (touchingTopOfRect) {
obj->m_dY = bounds.y - obj->m_dHeight;
obj->bottomContact = true;
}
// Bottom of Rect
if (touchingBottomOfRect) {
obj->m_dY = bounds.y + bounds.h;
obj->topContact = true;
}
// Left Side of rect.
if (touchingLeftOfRect) {
obj->m_dX = bounds.x - obj->m_dWidth;
obj->rightContact = true;
}
// Right Side of rect
if (touchingRightOfRect) {
printf("HIT RIGHT OF A OBSTACLE %d\n", bounds.w);
obj->m_dX = bounds.x + bounds.w;
obj->leftContact = true;
}
}
}
因此,每个帧都会调用它,并将循环存储我想要从对象可移动区域中排除的rects的数组。
使用这种方法开始工作变得非常棘手,很多时候条件会在他们不应该的时候开始。然而,我的主要问题是这对我来说似乎不必要地复杂化。有没有更好的方法来解决这个问题?
答案 0 :(得分:1)
您应该可以使用SDL_HasIntersection
基本伪代码将与
一致for each collider rect
if HasIntersection( bounds, colliderBounds )
find the centre points of each rect (x+w/2, y+h/2)
bool touchingLeft = ( bounds_centre.x < collider_centre.x )
bool touchingRight = ( bounds_cenre.x > collider_centre.x )
... etc ...
见
http://wiki.libsdl.org/SDL_HasIntersection
编辑:另一种选择是自己跳过任何碰撞检测,并使用优秀的Box2D代替: