C++精灵之间的 SDL 冲突

C++ SDL collision between sprites

本文关键字:SDL 冲突 之间 精灵 C++      更新时间:2023-10-16

经过30分钟的谷歌搜索,我能找到的就是这个:http://www.sdltutorials.com/sdl-collision

我认为标题具有误导性,然后我注意到这只是检测两个精灵之间碰撞的方法的噩梦。我想要的只是检查我的玩家精灵何时触摸其他东西(另一个精灵)。我怎样才能做到这一点?

我读到有一个名为 SDL_collision.h 的库,但它要么是 Pascal 的,要么是空的。

您很有可能会使用SDL_Rect作为边界框。其中xy是精灵的位置,wh是精灵的宽度和高度。然后您需要做的就是使用 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 + 高度"。使用它来修复该功能,以防我打错字。