不同类之间的C ++ SFML冲突检测

时间:2018-04-02 17:49:12

标签: c++ class collision sfml detection

我正在制作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!
} 

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

2 个答案:

答案 0 :(得分:0)

假设有两个对象' 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

答案 1 :(得分:0)

你必须转发声明你的类,以便让对方看到对方。

<强> 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"