我正在尝试构建一个基于组件的游戏引擎,但我的效率肯定是不足的。这个问题在我的冲突检测中最为明显,因为我会将每个GameObject与其他GameObject进行比较,以查看它们是否发生冲突。下面是碰撞检测函数:
void PhysicsSystem::update(float dt) {
std::vector<GameEngine::GameObject> moveObjects = manager->getAllObjectsWithComponent("move");
std::vector<GameEngine::GameObject> physicsObjects = manager->getAllObjectsWithComponent("physics");
for (int i = 0; i < moveObjects.size(); i++) {
MoveComponent* mComponent = static_cast<MoveComponent*>(manager->getComponentByType("move", moveObjects[i]));
PhysicsComponent* pComponent = static_cast<PhysicsComponent*>(manager->getComponentByType("physics", moveObjects[i]));
RenderComponent* rComponent = static_cast<RenderComponent*>(manager->getComponentByType("render", moveObjects[i]));
if (pComponent == nullptr || mComponent == nullptr || rComponent == nullptr) {
continue;
}
if (!pComponent->isSolid()) {
continue;
}
glm::vec4 coords1 = rComponent->getRenderCoords();
for (int j = 0; j < physicsObjects.size(); j++) {
PhysicsComponent* pComponent2 = static_cast<PhysicsComponent*>(manager->getComponentByType("physics", physicsObjects[j]));
RenderComponent* rComponent2 = static_cast<RenderComponent*>(manager->getComponentByType("render", physicsObjects[j]));
if (pComponent2 == nullptr || rComponent2 == nullptr) {
continue;
}
if (!pComponent2->isSolid()) {
continue;
}
glm::vec4 coords2 = rComponent2->getRenderCoords();
int dist = sqrt(pow((coords1.x - coords2.x), 2) + pow((coords1.y - coords2.y), 2));
if (dist > pComponent->getCollisionRadius()) {
continue;
}
if (GameEngine::Physics::checkCollision(coords1, coords2)) {
pComponent->addCollision(coords2);
}
}
}
我试图通过忽略与当前GameObject不接近的GameObjects来提高效率,使用碰撞半径,但这似乎没有任何作用,真正导致问题的代码行是
PhysicsComponent* pComponent2 = static_cast<PhysicsComponent*>(manager->getComponentByType("physics", physicsObjects[j]));
RenderComponent* rComponent2 = static_cast<RenderComponent*>(manager->getComponentByType("render", physicsObjects[j]));
它们调用我的GameObjectManager类中的一个函数。下面是该函数的代码:
Component* GameObjectManager::getComponentByType(std::string type, GameObject object) {
std::unordered_map<std::string, std::unordered_map<GLuint, Component*>>::iterator it = componentsByType.find(type);
if (it == componentsByType.end()) {
return nullptr;
}
std::unordered_map<GLuint, Component*>::iterator it2 = it->second.find(object.getGameObjectID());
if (it2 == it->second.end()) {
return nullptr;
}
return it2->second;
}
如果我去掉这两条线,游戏的速度就会显著提高。我有什么地方做错了吗?我认为在unordered_map中查找对象是一个恒定的时间操作,所以我不确定如何提高速度。有没有更有效的方法来处理我的组件?任何帮助都将不胜感激,谢谢!
https://stackoverflow.com/questions/52563219
复制相似问题