Wiem jak to zrobić, zanim wkleję kod, pewna uwaga:
Dopasuj ścieżkę pliku z czcionką odpowiednio do własnych zasobów, albo program zostanie "awaryjnie" wyłączony.
Oto kod:
#include <SFML/Graphics.hpp>
#include <iostream>
const std::string fontPath = "Resources/comic.ttf";
const sf::Vector2u windowDimensions = sf::Vector2u(800, 600);
class Player
{
public:
Player(sf::Font& font, sf::Vector2f position)
: shape(sf::Vector2f(100.f,100.f))
, text("Tekst",font)
{
text.setColor(sf::Color::Black);
}
void update(sf::Vector2f position)
{
sf::FloatRect textFrect = text.getGlobalBounds();
sf::FloatRect shapeFrect = shape.getGlobalBounds();
sf::Vector2f textPosition;
textPosition.x = shapeFrect.left + (shapeFrect.width - textFrect.width) * 0.5f;
textPosition.y = shapeFrect.top + (shapeFrect.height - textFrect.height) * 0.5f;
shape.setPosition(position);
text.setPosition(textPosition);
}
void draw(sf::RenderTarget& target) const
{
target.draw(shape);
target.draw(text);
}
private:
sf::RectangleShape shape;
sf::Text text;
};
int main()
{
sf::RenderWindow window(sf::VideoMode(windowDimensions.x, windowDimensions.y), "Example Application");
sf::Font font;
if (!font.loadFromFile(fontPath))
{
std::cout << "Failed to load file at: " << fontPath << std::endl;
return -1;
}
Player player(font, sf::Vector2f(300.f, 300.f));
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
window.close();
break;
}
}
player.update(static_cast<sf::Vector2f>(sf::Mouse::getPosition(window)));
window.clear();
player.draw(window);
window.display();
}
return 0;
}