C++ SFML 不同类之间的碰撞检测

标签 c++ class collision sfml detection

我正在制作 Frogger 的 C++ SFML 版本,目前正在尝试实现 Frog 和其他物体(汽车、卡车、原木等)之间的碰撞检测。我为 Frog 和游戏对象有单独的类,并希望使用边界框来检测交叉点,如下所示。

// get the bounding box of the entity
sf::FloatRect boundingBox = entity.getGlobalBounds();
// check collision with another box (like the bounding box of another 
entity)
sf::FloatRect otherBox = ...;
if (boundingBox.intersects(otherBox))
{
    // collision!
} 

我遇到的问题是,我不知道如何使用来自不同类的两个 Sprite 来完成这项工作,经过几天的搜索,我找不到如何做到这一点的解释。

最佳答案

假设有两个对象“a”和“b”,其中包含您要测试的 Sprite 。 然后您可以在代码中调用以下代码来测试它们之间的冲突:

#include "MyEntityA.hpp"
#include "MyEntityB.hpp"

MyEntityA entity_a;
MyEntityB entity_b;   

if(entity_a.getSprite().getGlobalBounds().intersects(entity_b.getSprite().getGlobalBounds()))
{
    // A collision happened.
}

查看此处了解更多信息:https://www.sfml-dev.org/tutorials/2.1/graphics-transform.php#bounding-boxes

关于C++ SFML 不同类之间的碰撞检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49616112/

相关文章:

c++ - 在 Visual Studio 中更新 C++ 项目的 DLL

c++ - 在 Qt 中无需分配即可将(很多!)数字转换为字符串的正确方法

c++ - 使用 -parallel 或(和)-vec 会使我们的程序运行得更快吗?

python - 从字典创建类实例?

javascript - 2d 方形到矩形碰撞检测和 Action (物理)

java - libGDX - 尝试实现 2 个 Sprite 之间的碰撞

c++ - 在 C++ 中使用指针 vector 时会泄漏内存吗?

c++ - 如何复制扩展 CCSprite 的实例?

java - 对象内存管理 Python 与 Java

java - Java 游戏的碰撞问题