如何解决这个“算术异常”?

时间:2017-04-12 16:31:37

标签: c++ sfml 2d-games

您好我正在使用SFML开发游戏,我遇到了一个功能问题。

这是代码:

enemy.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

Enemy.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);
    }
    }

Game.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();
   };

Game.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中,因为当我使用调试器时它停止在该函数中。

问题是什么,如何解决?

这个想法是敌人是一艘在Y轴上始终向下移动的船

1 个答案:

答案 0 :(得分:2)

这就是问题所在。你忘了使用不平等。 enimies.size()将始终返回true(如果有的话)。但你真的想要我&lt; enemies.size()。

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