gpt4 book ai didi

c++ - 如何解决这个 "arithmetic exception"?

转载 作者:行者123 更新时间:2023-11-30 03:32:41 24 4
gpt4 key购买 nike

您好,我正在使用 SFML 开发游戏,但我遇到了函数问题。

这是代码:

敌人.h:

    #ifndef ENEMY_H
#define ENEMY_H

#include<SFML/Graphics.hpp>

class Enemy {
private:
sf::Texture texture;
sf::Sprite enemySprite;

float enemySpeed;
int maxY, maxX;
public:
Enemy(int _maxY, int _maxX);
void render(sf::RenderWindow *wnd);
void update(sf::Time deltaTime);
void reset(float speed);
};

#endif

敌人.cpp:

    #include <ctime>

Enemy::Enemy(int _maxY, int _maxX) {
texture.loadFromFile("SFML-Game-Development-Book-
master/03_World/Media/Textures/Raptor.png");
enemySprite.setTexture(texture);
enemySprite.rotate(180);

maxY = _maxY;
maxX = _maxX;
}

void Enemy::render(sf::RenderWindow *wnd){
wnd->draw(enemySprite);
}

void Enemy::reset(float speed){
srand(time(NULL));
int num = rand();

enemySpeed = speed;

enemySprite.setPosition(num%maxX, maxY);
}

void Enemy::update(sf::Time deltaTime){
enemySprite.move(0.0f, enemySpeed * deltaTime.asSeconds());

if (enemySprite.getPosition().y > 600){
reset(enemySpeed);
}
}

游戏.h:

    class Game {
private:
sf::RenderWindow *mWindow;
Aircraft aircraft;
std::vector<Enemy> enemies;

void reset();
private:
void proccesEvent();
void update(sf::Time deltaTime);
void render();
public:
Game();
void run();
};

游戏.cpp:

Game::Game(){
mWindow = new sf::RenderWindow(sf::VideoMode(800,600), "ventana SFML");

for (int i=0; i<5; i++){
enemies.push_back(Enemy(800, 600));
}
}

void Game::proccesEvent(){
sf::Event event;

while(mWindow->pollEvent(event)){
if(event.type == sf::Event::Closed){
mWindow->close();
}
}
}

void Game::reset(){
for (int i=0; enemies.size(); i++){
enemies[i].reset(100.0f);
}
}

void Game::update(sf::Time deltaTime){
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)){
aircraft.Up();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)){
aircraft.Down();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)){
aircraft.Left();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)){
aircraft.Right();
}

aircraft.update(deltaTime);

for (int i=0; i<enemies.size(); i++){
enemies[i].update(deltaTime);
}
}

void Game::render(){
mWindow->clear();
aircraft.Render(mWindow);
for (int i=0; i<enemies.size(); i++){
enemies[i].render(mWindow);
}
mWindow->display();
}

void Game::run(){
sf::Clock clock;
while(mWindow->isOpen()){
sf::Time deltaTime = clock.restart();

proccesEvent();
reset();
update(deltaTime);
render();
}
}

我认为问题出在 Enemy 类中的函数 reset 中,因为当我使用调试器时它会在该函数中停止。

问题是什么,我该如何解决?

这个想法是 Enemy 是一艘沿 Y 轴始终向下移动的船

最佳答案

问题来了。你忘了使用不等式。 enimies.size() 将始终返回 true(如果有的话)。但你真的想要 i < enemies.size()。

void Game::reset(){
for (int i=0; i < enemies.size(); i++){
enemies[i].reset(100.0f);
}
}

关于c++ - 如何解决这个 "arithmetic exception"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43375019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com