矢量下标超出SFML游戏中的范围

Vector subscript out of range in SFML game

本文关键字:游戏 范围 SFML 下标      更新时间:2023-10-16

我正在开发一个游戏作为我的游戏开发课程的项目。它使用矢量在屏幕顶部生成敌人并向下跑,并创建由玩家和老板发射的"子弹"。在为他的项目符号添加老板和代码后,以前工作的代码现在抛出一个矢量下标超出范围错误。这个错误总是在击中敌人后立即抛出,在引入 Boss 之前不会发生。

bullets[i].shape.move(bullets[i].currVelocity);
//Bullet Removal
if (bullets[i].shape.getPosition().x < 0 || bullets[i].shape.getPosition().x > window.getSize().x
|| bullets[i].shape.getPosition().y < 0 || bullets[i].shape.getPosition().y > window.getSize().y) {
bullets.erase(bullets.begin() + i);
}
else {
//Collision Code
for (size_t k = 0; k < enemies.size(); k++) {
if (bullets[i].shape.getGlobalBounds().intersects(enemies[k].getGlobalBounds())) {
bullets.erase(bullets.begin() + i);
enemies.erase(enemies.begin() + k);
score = score + 1;
fiveScore = fiveScore + 1;
std::cout << "Score: " << score << std::endl;
hitSound.play();
if (fiveScore == 5) {
fiveScore = 0;
//scoreUpSound.play();
}
if (score >= 100 && bossSpawned == false) {
bossSpawned = true;
boss.setPosition(250.0f, 50.0f);
}
break;
}
}
if (bullets[i].shape.getGlobalBounds().intersects(boss.getGlobalBounds())) {
bullets.erase(bullets.begin() + i);
hitSound.play();
bossHP = bossHP - 1;
if (bossHP <= 0) {
bossSpawned = false;
boss.setPosition(3214.0f, 4322.0f);
text.setString("You have completed your quest." "n" "The warlock is slain and the realm is" "n" "safe, yet as life returns to the kingdom" "n" "you are dissatisfied. Your brother and" "n" "lover are both deceased and" "n" "you feel only death will heal your pain.");
text.setPosition(25.0f, 150.0f);
window.clear();
window.draw(text);
window.display();
Sleep(9000);
return 0;
}
break;
}
}
}

这是玩家子弹碰撞的代码。

b2.shape.setPosition(bossCenter);
b2.currVelocity = bossAimDirNorm * b2.maxSpeed;
bossbullets.push_back(BossBullet(b2));
}
for (size_t z = 0; z < bossbullets.size(); z++) {
bossbullets[z].shape.move(bossbullets[z].currVelocity);
//BossBullet Removal
if (bossbullets[z].shape.getPosition().x < 0 || bossbullets[z].shape.getPosition().x > window.getSize().x
|| bossbullets[z].shape.getPosition().y < 0 || bossbullets[z].shape.getPosition().y > window.getSize().y) {
bossbullets.erase(bossbullets.begin() + z);
}
else {
//Collision Code
if (bossbullets[z].shape.getGlobalBounds().intersects(player.getGlobalBounds())) {
bossbullets.erase(bossbullets.begin() + z);
playerDead = true;
text.setString("You have failed your quest.");
text.setPosition(150.0f, 150.0f);
window.clear();
window.draw(text);
window.display();
Sleep(5000);
return 0;
}
}
}

这是老板子弹碰撞的代码。任何帮助甚至可能出错的想法都会有所帮助。恢复到我添加老板之前是我现在找到的唯一解决方案。

您在循环使用矢量时正在从矢量中删除。这会更改矢量的大小,这通常是错误的根源。

看看 删除循环内向量的元素

寻找一种方法。