不同 类 之间的 C++ SFML 碰撞检测
C++ SFML collision detection between different classes
我正在制作 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!
}
我遇到的问题是,我不知道如何使用来自不同 类 的两个 sprite 进行这项工作,经过几天的搜索后,我找不到如何做的解释。
假设有两个对象 '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
您必须转发声明您的 类 才能让对方看到对方。
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"
我正在制作 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!
}
我遇到的问题是,我不知道如何使用来自不同 类 的两个 sprite 进行这项工作,经过几天的搜索后,我找不到如何做的解释。
假设有两个对象 '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
您必须转发声明您的 类 才能让对方看到对方。
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"