나는 소행성이 화면 아래로 떨어지는 C++ 및 sfml이있는 게임에서 플레이어가 레이저를 쏘아서 파괴합니다. 소행성이나 레이저가 화면의 떨어져 갈 때, 그들은 삭제 및 해당 표준 : : 벡터에서 삭제됩니다포인터를 실행할 때의 C++ 액세스 위반
소행성 :
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의 메서드를 사용하여 충돌을 확인합니다. 나는이에 몇 시간을 보냈어요 내가없는 것
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.
}
}
:
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 방법 무슨 일이 일어나고 있는지 알아 내려고. 나는 포인터와 인덱스를 안전하게 지우고 있다고 생각하기 때문에 거기에서 어디로 가야할지 모르겠습니다. 참고로, isColliding 함수는 두 개의 별개 GameObjects (플레이어와 소행성)에서 작동합니다. 문제가 모든 소행성을 반복하는 것과 관련이있는 것처럼 보입니다.
도움 주셔서 감사합니다.
업데이트] 소행성 삭제 :
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 asteroids.size() - 1'는 사실입니다! –
aschepler