我正在使用 SFML 开发 Flappy Bird 克隆,但无法正确渲染管道。小鸟精灵渲染得很好,但管道没有显示在屏幕上。
我创建了一个 Bird 类,用于处理鸟的运动和绘制,以及生成和绘制管道。我已经检查了我的代码好几次,但我似乎无法找出导致问题的原因。
以下是重要的代码部分
#include <SFML/Graphics.hpp>
#include <vector>
#include <cstdlib>
class Bird {
public:
Bird();
void drawObs(sf::RenderWindow& window);
void update(sf::RenderWindow& window);
private:
void initVars();
static sf::Texture obs3Texture;
static sf::Texture obs2Texture;
static sf::Texture obs1Texture;
static sf::Sprite obs3Sprite;
std::vector<sf::Sprite> pipes;
float pipeSpeed;
float timeSinceLastSpawn;
};
Bird::Bird() {
initVars();
pipeSpeed = 200.0f;
timeSinceLastSpawn = 0.0f;
}
void Bird::drawObs(sf::RenderWindow& window) {
int randomNum = rand() % 3 + 1;
sf::Sprite pipeSprite;
if (randomNum == 1) {
pipeSprite.setTexture(obs1Texture);
}
else if (randomNum == 2) {
pipeSprite.setTexture(obs2Texture);
}
else {
pipeSprite.setTexture(obs3Texture);
}
pipeSprite.setScale(1.5f, 1.5f);
pipeSprite.setPosition(window.getSize().x, 0);
pipes.push_back(pipeSprite);
}
void Bird::initVars() {
obs3Texture.loadFromFile("images/Pipe3.png");
obs2Texture.loadFromFile("images/Pipe2.png");
obs1Texture.loadFromFile("images/Pipe1.png");
obs3Sprite.setTexture(obs3Texture);
}
void Bird::update(sf::RenderWindow& window) {
timeSinceLastSpawn += 0.1f;
const float spawnCooldown = 2.0f;
if (timeSinceLastSpawn >= spawnCooldown) {
drawObs(window);
timeSinceLastSpawn = 0.0f;
}
for (const auto& pipe : pipes) {
window.draw(pipe);
}
for (size_t i = 0; i < pipes.size(); ++i) {
pipes[i].move(-pipeSpeed * 0.1f, 0);
if (pipes[i].getPosition().x + pipes[i].getGlobalBounds().width < 0) {
pipes.erase(pipes.begin() + i);
}
}
}
int main() {
sf::RenderWindow window(sf::VideoMode(800, 600), "Flappy Bird");
Bird bird;
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
bird.update(window);
window.display();
}
return 0;
}
仔细检查管道精灵的定位和缩放。 验证了生成和绘制管道的逻辑。 确保从更新函数调用drawObs函数。
只有小鸟渲染,管道仍然不会生成
谢谢!
使用unity引擎代替SFML