谷歌搜索 30 分钟后,我只能找到以下内容: http://www.sdltutorials.com/sdl-collision
我认为这个标题具有误导性,然后我注意到它只是一种检测两个 Sprite 之间碰撞的方法的噩梦。我只想检查我的玩家 Sprite 何时接触到其他东西(另一个 Sprite )。我怎样才能做到这一点?
我读到有一个名为 SDL_collision.h 的库,但它要么是 Pascal 语言要么是空的。
最佳答案
您可能会使用 SDL_Rect
为您的边界框。 x
和 y
是 Sprite 的位置,w
和 h
是 Sprite 的宽度和高度 Sprite 。然后你需要做的就是使用 SDL_HasIntersection
.
这是一个简单的例子:
SDL_Surface *Srfc1, *Srfc2;
Srfc1= IMG_Load("foo.png");
Srfc2= Srfc1;
Srfc2->refcount++;
SDL_Rect box1, box2;
box1.x = box1.y = 0;
box2.x = box2.y = 100;
box1.w = box2.w = Srfc1->w;
box2.h = box2.h = Srfc1->h;
// ... somewhere in your event handling logic
if (SDL_HasIntersection(&box1, &box2))
{
printf("Collision.");
}
// ...
SDL_FreeSurface(Srfc1);
SDL_FreeSurface(Srfc2);
由于您没有SDL_HasIntersection
,这里有一个快速的小函数可以满足您的需要:
bool IntersectRect(const SDL_Rect * r1, const SDL_Rect * r2)
{
return !(r2->x > (r1->x + r1->w) ||
(r2->x + r2->w) < r1->x ||
r2->y > (r1->y + r1->h) ||
(r2->y + r2->h) < r1->y);
);
}
引用逻辑是:
return !(r2.left > r1.right ||
r2.right < r1.left ||
r2.top > r1.bottom ||
r2.bottom < r1.top);
其中“右”和“底”分别指的是“x + 宽度”和“y + 高度”。使用它来修复函数,以防我打错字。
关于 Sprite 之间的 C++ SDL 碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20722531/