参考 window 绝对位置的 SFML 绘图

SFML drawing on absolute position with reference to window

我目前的sfml项目有一些看法。视图改变大小和中心。我可以用数学计算出我想要的位置,但这似乎工作量太大了。是否存在我可以使用的内置函数?

是的,您可以按如下方式使用 sf::RenderWindow::getDefaultView()(假设您有一个名为 windowsf::RenderWindow):

// First draw all objects that you have set a view for
window.setView(yourView);

window.draw(viewObject);

window.setView(window.getDefaultView()); // Reset the view to the window's default one

// ... Set the position and all (You can do this before as well)

window.draw(yourScoreBoard);

window.display(); // You should see your views with a score board overlay that
                  // stays in the same place

如果你想绘制有自己视图的东西,那么首先将 window 的视图设置为该视图,然后再绘制你的对象。

如您所说,您需要叠加层。 UI 覆盖是使用单独的渲染纹理完成的。您应该将游戏拆分为两个渲染目标:

  • in-game 事物(玩家、怪物、法术等)的渲染目标
  • UI(分数、健康等)的渲染目标

两个渲染目标也是纹理 (sf::RenderTexture)。您将所有内容呈现给他们,因为它们很简单 windows。一旦将它们放在单独的纹理中,就可以使用它们在 window:

中使用精灵来渲染所有内容
sf::RenderTexture inGameRT;
sf::RenderTexture uiRT;

while(window.isOpen())
{
    // event loop

    // now drawing in-game (only example):
    inGameRT.clear();
    // std::vector<sf::Sprite*> players; // or sth other...
    for(auto const & player : players)
         inGameRT.draw(*player);

    inGameRT.display(); // don't forget it



    // now drawing UI (only example):
    uiRT.clear();
    // std::vector<sf::Sprite*> uiWidgets; // or sth other...
    for(auto const & widget : uiWidgets)
         uiRT.draw(*widget);

    uiRT.display(); // don't forget it

    // Once you drawn everything, you can display two textures inside window

    window.clear();

    sf::Sprite inGameSprite{inGameRT.getTexture()};
    sf::Sprite uiSprite{uiRT.getTexture()};
    window.draw(inGameSprite);
    window.draw(uiSprite);
    window.display();
}

sf::Views 也可以应用于 sf::RenderTargets.