【发布时间】:2015-06-07 08:36:09
【问题描述】:
我在学校做一个小组项目,我们正在创建一个 2d 游戏,但我遇到了一个异常,我不知道该怎么办。
附注:所有这些都是在调试模式下完成的。
我们有一个物理引擎类,可以计算碰撞并向实体添加矢量力,代码:
void PhysicsEngine::doPhysicsTick()
{
vector<vector<unordered_set<Entity*>>> *grid = this->grid.getGrid();
unordered_set<Entity*>* updatable = new unordered_set<Entity*>();
unordered_set<Entity*>* collidable = new unordered_set<Entity*>();
const int &r = CollisionGrid::C_GRID_RADIUS;
for (int row = 0; row < grid->size(); row++)
for (int col = 0; col < grid->at(row).size(); col++)
{
collidable->clear();
// put all surrounding grid blocks in a entity list to
// check against collision with the current block
int rw(row - r > 0 ? row - r : 0);
int cl(col - r > 0 ? col - r : 0);
for (int rrow = rw; rrow <= row + r && rrow < grid->size(); rrow++)
for (int rcol = cl; rcol <= col + r && rcol < grid->at(rrow).size(); rcol++)
for (Entity *e : grid->at(rrow).at(rcol)) // It crashes here
collidable->insert(e);
for (Entity *e : grid->at(row).at(col))
{
if (e->isFixed())
continue;
e->speed += gravity;
eBounds.reBox(e->location, e->getSize() + e->speed);
for (Entity *c : *collidable)
if (isOverlapping(eBounds, Box(c, c->getSize())) && e != c)
doCollision(e, c);
updatable->insert(e);
}
}
我们有一个单独的碰撞网格类来管理我们存储实体以进行碰撞检查的网格(因此我们不必检查所有内容)
碰撞网格及其底层vector 是在物理引擎的构造函数被调用PhysicsEngine::PhysicsEngine(World *world) : grid(world) 时创建的。但出于某种原因,仅在第一个刻度上,我看到矢量网格指向循环内部不存在的东西(尺寸大得离谱等),填充可碰撞。
它抛出的错误在标题中。如果我在它周围放置一个 catch 块,它只会在某些 c++ 库中的其他地方随机崩溃(每次不同的文件)
如果我不评论我放在那里的东西,由于某种原因,它会在我们的 gameloop 类(物理引擎的调用滴答声)析构函数中崩溃。
Gameloop::~Gameloop()
{
//if( t ) // t = #include <thread>
// delete t;
}
我们不允许使用 Win32 API 之外的任何库和一些默认的 c++ 库
编辑:我添加了一些图片(并且取消了 unordered_sets 的动态分配)
它应该显示什么:
它有时会在第一个刻度上显示: (注意指针是一样的,前两次投篮是在同一次跑动中投的)
它在第一次滴答时显示的其他时间:
【问题讨论】:
-
您是否有任何理由动态分配 STL 容器?
-
@DavidHaim 我希望在堆栈上节省一些空间,尽管我什至不确定它是否能做到(我们的老师并没有准确地给我们关于这个主题的太多信息)
-
您不会节省那么多,因为大多数容器(
std::array是一个例外)无论如何都会动态分配其内容。容器类本身很少超过几个指针。内容不在堆栈中。 -
检查您的索引。它们几乎肯定是越界的。
-
@LightningRacisinObrit 但为什么呢?他们不应该与我正在做的所有
i < grid->size()在一起
标签: c++