我正在制作游戏,并且尝试通过bool shouldDie == true找到敌人。
我有一个敌人std::list,我个人不知道代码出了什么问题。
如果敌人的shouldDie == true,那么我将播放动画。
希望您能帮助我理解我为什么得到此错误。
我也没有重载==运算符,我已经在线搜索了,不确定是否有必要...
bool foundEnemy(Enemy& enemy)
{
return enemy.shouldDie == true;
}
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();
}
}
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;
};
最佳答案
该错误实际上不在您认为的位置,而是以下几行。
if (animationCounter >= 8)
{
enemies.remove(*enemy); // here
}
您正在使用
std::list::remove
函数,该函数将搜索列表中与给定元素匹配的任何元素并将其删除。要知道哪个元素与给定的相同,它需要知道如何比较它们,因此需要operator ==
请改用
std::list::erase()
-此函数接受迭代器,并将删除您指向的确切元素。if (animationCounter >= 8)
{
enemies.erase(enemy); // no dereference of the iterator
}
旁注-编译器是非常有用的工具。如果它检测到错误,它将使您指向发生错误的直线和列,尽管有时此信息可以很好地隐藏在大量其他(不太有用)的打印物中。
如果您还不了解编译器的语言,则可以将整个错误消息复制并粘贴到您的SO问题中,这将有助于我们更快地诊断错误。
关于c++ - 二进制 '==':找不到使用 'Enemy'类型的左操作数的运算符(或者没有可接受的转换),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59471902/