【问题标题】:C++ SFML collision detection between different classes不同类之间的 C++ SFML 碰撞检测
【发布时间】:2018-09-11 22:56:19
【问题描述】:

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

// 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!
} 

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

【问题讨论】:

    标签: c++ class collision sfml detection


    【解决方案1】:

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

    #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

    【讨论】:

    • 我遇到的问题是这两个精灵来自不同的头文件和 cpp 文件,所以当我尝试这样做时,其中一个精灵是未定义的。我的 frogSprite 在我的 frog.cpp 中,而其他游戏对象(例如汽车)在我的 game.cpp 中。问题是我不知道如何检查碰撞,因为它们不在我的代码的同一部分。
    • 我认为您遇到的问题并非特定于 sfml,而是一般的 C++ 编程。例如,如果您有 Game.hpp,则在其中包含“ClassA.hpp”和“ClassB.hpp”,然后创建这些类的对象并使用这些对象测试碰撞。这有帮助吗?
    • 这个解释很有道理,我现在就去修复它。谢谢。
    【解决方案2】:

    你必须转发声明你的类才能让彼此看到对方。

    carsprite.h

    class FrogSprite; //declare your FrogSprite here
    
    class CarSprite
    {
    
    };
    

    frogsprite.h

    class CarSprite;
    
    class FrogSprite
    {
    
    };
    

    之后,您可以在其 cpp 文件中包含头文件以查看类的完整定义。

    carsprite.cpp

    #include "frogsprite.h"
    

    frogsprite.cpp

    #include "carsprite.ccp"
    

    【讨论】:

      猜你喜欢
      • 2017-07-25
      • 2023-03-24
      • 1970-01-01
      • 2015-02-01
      • 2015-10-07
      • 2018-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多