【发布时间】:2018-04-17 20:07:15
【问题描述】:
我正在使用 c++ 和 sfml 制作一个游戏,其中有小行星从屏幕上掉下来,玩家发射激光来摧毁它们。当小行星或激光离开屏幕时,它们会从各自的 std::vectors 中删除和擦除:
小行星:
std::vector<Asteroid*>::iterator it;
for (it = asteroids.begin(); it < asteroids.end(); ) {
(*it)->update(dt);
if ((*it)->getPosition().y > Game::window.getSize().y) {
delete * it;
asteroids.erase(it);
}
else {
it++;
}
}
激光:
for (int i = 0; i < lasers.size(); i++) {
lasers.at(i)->update(dt);
if (lasers.at(i)->getPosition().y < 0) {
delete lasers.at(i);
lasers.erase(lasers.begin() + i);
i--;
}
}
当我尝试检测它们之间的冲突时,问题就出现了。我循环遍历每个激光实例中的所有小行星,并使用父类 GameObject 中的方法检查它们之间的碰撞。
for (int i = 0; i < Game::spawner->asteroids.size() - 1; i++) {
if (isColliding(asteroids.at(0))) { // Access violation executing location 0x071DE528.
printf("collided");
//delete asteroids.at(i);
//asteroids.erase(asteroids.begin() + i);
break;
}
}
这里是isColliding和getPosition方法:
bool GameObject::isColliding(GameObject * g) {
sf::Vector2f gPos = g->getPosition();
sf::Vector2f pos = this->getPosition(); // after waiting a few seconds and then testing the collision, I get this error here: Access violation executing location 0x00000000.
if (gPos.x <= pos.x && pos.x <= gPos.x + g->width
|| pos.x <= gPos.x && gPos.x <= pos.x + width) {
if (gPos.y <= pos.y && pos.y <= gPos.y + g->height
|| pos.y <= gPos.y && gPos.y <= pos.y + height) {
return true;
}
}
return false;
}
sf::Vector2f GameObject::getPosition() {
if (isLoaded) {
if (animated)
return animatedSprite.getPosition();
else
return sprite.getPosition(); // the asteroids are not animated, so this will be called.
}
}
我在这上面花了几个小时,但我似乎无法弄清楚发生了什么。我想我正在安全地删除指针及其索引,所以我不知道从那里去哪里。作为参考,isColliding 函数确实适用于两个不同的游戏对象(玩家和小行星)。似乎这个问题与所有小行星的循环有关。
感谢您的帮助。
更新的小行星删除:
int toDelete = -1;
for (int i = 0; i < asteroids.size(); i++) {
asteroids.at(i)->update(dt);
if (asteroids.at(i)->getPosition().y > Game::window.getSize().y) {
toDelete = i;
}
}
if (toDelete != -1) {
delete asteroids.at(toDelete);
asteroids.erase(asteroids.begin() + toDelete);
}
【问题讨论】:
-
你不能像这样遍历一个向量,也不能在上面调用
erase。 -
如果
asteroids为空,那么i < Game::spawner->asteroids.size() - 1为真!
标签: c++ pointers sfml access-violation