问题描述
我试图每隔固定的秒数创建一个 Sprite, 问题是精灵呈现为白色方块。
PowerUp.h
#pragma once
#include <SFML/Graphics.hpp>
#include <stdlib.h>
#include "Utility.h"
class PowerUp
{
public:
PowerUp(sf::Vector2f position,PowerUpType powerUpType);
void draw(sf::RenderWindow& window);
private:
sf::Image image;
sf::Texture texture;
sf::Sprite sprite;
sf::Vector2f position;
float radius;
float delay;
PowerUpType type;
sf::Clock timer;
};
PowerUp.cpp
#include "PowerUp.h"
PowerUp::PowerUp(sf::Vector2f position,PowerUpType type) {
this->position = position;
this->type = type;
this->image.loadFromFile("Images/img1.png");
this->sprite.setorigin(sf::Vector2f(2 * radius,2 * radius));
this->sprite.setPosition(position);
this->texture.loadFromImage(this->image);
this->sprite.setTexture(this->texture);
radius = 25;
delay = 5;
sprite.setScale(0.5f,0.5f);
}
void PowerUp::draw(sf::RenderWindow &window) {
window.draw(this->sprite);
}
Board.h
#pragma once
#include <SFML/Graphics.hpp>
#include <stdlib.h>
#include "Utility.h"
#include "PowerUp.h"
class Board {
public:
Board(int width,int height);
void updatePowerUp();
void draw(sf::RenderWindow& window);
private:
sf::Vector2f size;
sf::Vector2f offset;
sf::RectangleShape background;
sf::Clock timer;
std::vector<PowerUp> powerUps;
float nextPowerUp;
};
PowerUp.cpp
#include "Board.h"
Board::Board(int width,int height) {
size = sf::Vector2f(width,height);
offset = sf::Vector2f(5,5);
background.setoutlineColor(sf::Color::White);
background.setSize(size - 2.f * offset);
background.setoutlineThickness(offset.x);
background.setFillColor(sf::Color::Transparent);
background.setPosition(offset);
nextPowerUp = 1.f;
}
void Board::updatePowerUp() {
if (timer.getelapsedtime().asSeconds() > 1) {
PowerUp p(sf::Vector2f(randFloat(size.x - 40),randFloat(size.y - 40)),PowerUpType::CLEAN_BOARD);
powerUps.push_back(p);
nextPowerUp = 5 + randFloat(6);
timer.restart();
}
}
void Board::draw(sf::RenderWindow &window) {
window.draw(background);
for (PowerUp pu : powerUps) {
pu.draw(window);
}
}
main.cpp
#include <SFML/Graphics.hpp>
#include <stdlib.h>
#include "Utility.h"
#include "Board.h"
using namespace std;
int main()
{
const int height = 800;
const int width = 800;
sf::ContextSettings windowSettings;
windowSettings.antialiasingLevel = 16;
sf::RenderWindow window(sf::VideoMode(height,width),"CurveFever",sf::Style::Default,windowSettings);
Board myBoard = Board(width,height);
myBoard.setColor(sf::Color::Green);
sf::Clock deltaTime;
while (window.isopen()) {
myBoard.updatePowerUp();
window.clear();
myBoard.draw(window);
window.display();
sf::Event ev;
while (window.pollEvent(ev)) {
if (ev.type == sf::Event::Closed)
window.close();
}
}
return 0;
}
我发现如果我在 PowerUp.cpp 中重复 this->image.loadFromFile("Images/img1.png")
两次,只有第一个精灵不会显示为白色方块。
我知道这个问题通常会发生,因为没有对纹理的引用,但只要 PowerUp 对象存在,纹理就应该存在。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)