您好我正在使用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; i<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();
}
}
问题在于&#34;敌人&#34;不会出现在屏幕上。纹理正确加载,如果我从类游戏中运行的函数中删除函数重置,则会出现一个白色方块而不是纹理,当时还有一个,所以如何纠正这个,以便同时显示多个敌人。