我正在制作一个游戏,我正在尝试使用 bool shouldDie == true 找到敌人。我有一个 Enemy std::list,我个人不知道代码有什么问题。如果敌人有 shouldDie == true 我只会播放动画。希望您能帮助我理解为什么我会收到错误消息。
此外,我没有重载 == 运算符,我在网上搜索过,但不确定是否有必要...
bool foundEnemy(Enemy& enemy)
{
return enemy.shouldDie == true;
}
Run Code Online (Sandbox Code Playgroud)
void Enemy::PlayDeathAnimation(std::list<Enemy>& enemies)
{
dead = true;
auto it = std::find_if(enemies.begin(), enemies.end(), foundEnemy); // where I think the error is
auto enemy = std::next(it, 0);
if (animationClock.getElapsedTime().asSeconds() >= 0.05f)
{
enemy->icon.setTextureRect(animationFrames[animationCounter]);
if (animationCounter >= 8)
{
enemies.remove(*enemy);
}
animationCounter++;
animationClock.restart();
}
}
Run Code Online (Sandbox Code Playgroud)
class Enemy : public Entity
{
public:
Enemy() {}
Enemy(sf::Vector2f position, sf::Texture* texture,Player* target);
~Enemy();
void Update(sf::RenderWindow* window, float tElapsedTime);
void Draw(sf::RenderWindow* window);
void Fire(float tElapsedTime);
void CheckBullets();
void CheckEnemyBullets();
void CheckHealth();
void SetPosition(float x, float y);
bool shouldDie = false;
void PlayDeathAnimation(std::list<Enemy>& enemies);
private:
bool dead = false;
sf::Texture* deathSpriteSheet;
std::vector<sf::IntRect> animationFrames;
std::vector<Bullet> bullets;
sf::RectangleShape origin;
sf::RectangleShape aim;
Player* target;
int animationCounter = 0;
sf::Clock animationClock;
};
Run Code Online (Sandbox Code Playgroud)
错误实际上不在您认为的位置,而是在下面几行。
if (animationCounter >= 8)
{
enemies.remove(*enemy); // here
}
Run Code Online (Sandbox Code Playgroud)
您正在使用std::list::remove函数,它将搜索与给定元素匹配的列表中的任何元素并删除它们。要知道哪个元素与给定的元素相同,它需要知道如何比较它们,因此需要operator ==
使用std::list::erase()代替-此函数接受一个迭代器,并会删除确切元素你点。
if (animationCounter >= 8)
{
enemies.erase(enemy); // no dereference of the iterator
}
Run Code Online (Sandbox Code Playgroud)
旁注 - 编译器是非常有用的工具。如果它检测到错误,它会将您指向发生错误的直接行和列,尽管有时这条信息很好地隐藏在大量其他(不太有用的)打印件中。
如果您不了解编译器的语言(还),您可以将整个错误消息复制并粘贴到您的 SO 问题中,这将帮助我们更快地诊断错误。