Я создал класс Bird, который обрабатывает движение и рисование птицы, а также генерирует и рисует трубы. Я проверил свой код несколько раз, но не могу понять, в чем причина проблемы.
вот важные части кода
Код: Выделить всё
#include
#include
#include
class Bird {
public:
Bird();
void drawObs(sf::RenderWindow& window);
void update(sf::RenderWindow& window);
private:
void initVars();
static sf::Texture birdTexture;
static sf::Texture obs3Texture;
static sf::Texture obs2Texture;
static sf::Texture obs1Texture;
static sf::Sprite birdSprite;
static sf::Sprite obs3Sprite;
std::vector pipes;
float gravity;
float velocityY;
float maxVelocityY;
float jumpVelocity;
float groundY;
float pipeSpeed;
float timeSinceLastSpawn;
};
Bird::Bird() {
initVars();
gravity = 1300.0f;
velocityY = 0.0f;
jumpVelocity = 650.0f;
groundY = 1100.0f;
maxVelocityY = 1000.0f;
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() {
birdTexture.loadFromFile("images/FlappyBird.png");
obs3Texture.loadFromFile("images/Pipe3.png");
obs2Texture.loadFromFile("images/Pipe2.png");
obs1Texture.loadFromFile("images/Pipe1.png");
birdSprite.setTexture(birdTexture);
obs3Sprite.setTexture(obs3Texture);
}
void Bird::update(sf::RenderWindow& window) {
velocityY += gravity * 0.1f;
if (velocityY > maxVelocityY) {
velocityY = maxVelocityY;
}
float newY = birdSprite.getPosition().y + velocityY * 0.1f;
birdSprite.setPosition(birdSprite.getPosition().x, newY);
if (newY > groundY) {
birdSprite.setPosition(birdSprite.getPosition().x, groundY);
velocityY = 0.0f;
}
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 вызывается из функция обновления.
Рендерится только птица, а трубы всё равно не спавнятся
спасибо!
Подробнее здесь: https://stackoverflow.com/questions/784 ... -bird-game