c++ - 视觉 C++ RECT 碰撞

标签 c++ visual-studio-2010 collision-detection

几天前,我刚刚开始使用 Win32 GUI 编程。我正在尝试制作一个简单的游戏,我需要在其中检测两个物体之间的碰撞。 所以我使用 RECT 结构

制作了我的角色

为了检测它们是否发生碰撞,我使用了:

// Returns 1 if the point (x, y) lies within the rectangle, 0 otherwise
int is_point_in_rectangle(RECT r, int x, int y) {
    if ((r.left   <= x && r.right >= x) &&
        (r.bottom <= y && r.top   >= y))
        return 1;
    return 0;
}

// Returns 1 if the rectangles overlap, 0 otherwise
int do_rectangles_intersect(RECT a, RECT b) {
    if ( is_point_in_rectangle(a, b.left , b.top   ) ||
         is_point_in_rectangle(a, b.right, b.top   ) ||
         is_point_in_rectangle(a, b.left , b.bottom) ||
         is_point_in_rectangle(a, b.right, b.bottom))
        return 1;
    if ( is_point_in_rectangle(b, a.left , a.top   ) ||
         is_point_in_rectangle(b, a.right, a.top   ) ||
         is_point_in_rectangle(b, a.left , a.bottom) ||
         is_point_in_rectangle(b, a.right, a.bottom))
        return 1;
    return 0;
}

这是我在这里的一个问题上发现的,它似乎适用于 this 这样的情况。 .但是这种情况有一个小问题here

有什么办法可以解决吗?我做错了吗?我应该尝试不同的方法吗? 任何提示都会有所帮助。

最佳答案

很明显,检查一个矩形的角是否在另一个矩形内部是个坏主意:

Intersecting rectangles

一个简单的检查方法是:

if (a.left >= b.right || a.right <= b.left ||
    a.top >= b.bottom || a.bottom <= b.top) {

   // No intersection

} else {

   // Intersection

}

关于c++ - 视觉 C++ RECT 碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15550879/

相关文章:

c++ - Floyd 算法使用 (const vector<int>& t : flights), 存储在 't' 上的值是什么

c++ - 大型文本文件查看器如何工作?如何构建大型文本阅读器

c++ - Visual Studio 2010 项目文件中的条件

c++ - 如何检测来自不同类的 QGraphicsItem 和 QGraphicsPixmapItem 图像之间的冲突

c++ - 需要帮助使用分离轴定理实现碰撞检测

c++ - 在 C/C++ 中声明这些类型的表的简洁方法?

c++ - 如何迭代所有 malloc block (glibc)

visual-studio-2010 - Visual Studio 2010 外部库 API 文档

c# - 需要一个用于 C# .Net 的实时、自动、后台编译器和测试运行器

javascript - JS 贪吃蛇游戏中的碰撞检测错误