无法让我的 FPS 号码与 SFML 一起显示 fps.cppGame.cpp仅限 SFML 初始化和游戏循环

问题描述

  1. 我正在制作一个程序,需要在屏幕左上角列出我的 FPS 计数器。我正在使用 SFML 将我的程序输出到窗口中。
  2. 我有一个 FPS.cpp 文件,其中包含我的 FPS 计数器的类。这个类中有两个方法,“getFPS()”和“update()”。

fps.cpp

#include <SFML/Graphics.hpp>
#include <iostream>

class FPS
{
public:
   FPS() : mFrame(0),mfps(0) {}


   const unsigned int getFPS() const { return mfps; }
private:
   unsigned int mFrame;
   unsigned int mfps;
   sf::Clock mClock;

public:
   void update()
   {
       if (mClock.getelapsedtime().asSeconds() >= 1.f)
       {
           mfps = mFrame;
           mFrame = 0;
           mClock.restart();
       }

       ++mFrame;
   }
};

Game.cpp(仅限 SFML 初始化和游戏循环)

int Game::run()
{
    //Prepare the Window
    window.create(VideoMode(1920,1080),"GameWindow",Style::Fullscreen);

    FPS fps;
    Text fpsNum;
    sf::Font font;
    font.loadFromFile("fonts/KOMIKAP_");
    fpsNum.setFont(font);
    fpsNum.setCharacterSize(75);
    fpsNum.setFillColor(Color::Green);
    fpsNum.setPosition(20,20);

    while (window.isopen())
    {
        Event event;
        while (window.pollEvent(event))
        {
            if (Keyboard::isKeypressed(Keyboard::Escape))
            {
                window.close();
            }
        }

        

        //Update
        fps.update();
        std::cout << fps.getFPS() << std::endl;
        std::ostringstream ss;
        ss << fps.getFPS();
        fpsNum.setString(ss.str());

        //Draw
        window.clear();
        
        
        window.draw(fpsNum);
        window.display();
    }

    
    return 0;
}
  1. 当我运行 std::cout << fps.getFPS() << std::endl; 时,控制台中会显示正确的 FPS,所以我知道 getFPS() 正在完成它的工作。据我了解,问题在于 SFML 如何显示实际文本,因为我在屏幕上看到的只是 FPS 应该位于的绿点。

图片 Picture of the output,note the green dot at the top left corner.

注意:我知道这里没有显示主要功能,我没有理由显示代码,因为它与问题无关。

编辑:我还尝试在 fpsNum.setString("hello");显示静态“Hello”,但它也没有显示

解决方法

您是否尝试只放置纯文本而不是 fps 计数?您可以尝试检查其他字体是否可以工作,或者如果文件未加载则抛出错误。

if (!font.loadFromFile("fonts/KOMIKAP_")) {
    std::cout << "Error with the file" << std::endl;
}

如果出现错误,请尝试将 .ttf 添加到字体中?