I used this for CircleShape. It works fine.
sf::Vector2f getPositionForText (const sf::CircleShape& shape,
const sf::RenderWindow& window,
const sf::View& viewFrom,
const sf::View& viewTo)
{
float radius = shape.getRadius();
sf::Vector2f center {shape.getPosition().x, shape.getPosition().y};
sf::Vector2i positionInWindow = window.mapCoordsToPixel(center,viewFrom);
center = window.mapPixelToCoords (positionInWindow, viewTo);
center += sf::Vector2f {-radius * shape.getScale().x, -radius * shape.getScale().y}
* (viewTo.getSize().x / viewFrom.getSize().x);
return center;
}
// and calling this function
text3.setPosition(getPositionForText(entity2, window, mainView, textView)
+ sf::Vector2f{0.f, -textSpaceHeight}); // text offset
Thinking about doing similar for any sf::Shape or VertexArray. I am thinking about 2 ways:
1. through bounding box- getting sf::FloatRect bounding box of the entity
- transform between views using sf::Transform
- getting a new bounding box from a transformed bounding box
Advantages: relatively simple and probably reasonably fast
Disadvantages: position of text will be simplified as in the bounding box from the transformed bounding box could be large, especially if the transformed bounding box is at 45°.
2. through transforming entity- copy entity
- transform entity between views
- finding the bounding box from the transformed entity
Advantages: Much more precise as the bounding box is found on top of transformed entity
Disadvantages: If there are many text labels over an entity it practically make no sense for the view and all these entities need to be copied transformed one by one