1

我正在使用 sfml 2.0 制作游戏。背景将是一个星空。与其使用图像,我认为每次游戏启动时随机生成一个星空可能会很整洁,因此每次背景看起来都略有不同。问题是,我目前的做法会大大降低我的游戏速度。有谁知道是什么原因导致速度下降?我浏览了文档以查看内容,但我没有找到任何东西...

这是我的代码:

#include <SFML/Graphics.hpp>
#include "sfml helper/initialization_helpers.h"
#include "sfml helper/cursor_functions.h"
#include "sfml helper/global_event_handler.h"
#include "sfml helper/globals.h"
#include <cstdio>

int main(int argc, char* argv[])
{
    try {
        // some non-related preparations...
        PrepareApplication(argv[0]);
        float width = 640, height = 480;
        sf::RenderWindow window(sf::VideoMode(width, height), "SFML Test", sf::Style::Close);
        window.setFramerateLimit(60);

        // Textures is a global object that has an internal std::map<string, sf::Texture>
        Textures.add("ball.png", "ball");
        sf::Sprite sprite;
        sprite.setTexture(Textures.get("ball"));

        // This is the snippet that generates the starfield
        srand(time(NULL));
        sf::Image starsImg;
        starsImg.create(width, height, sf::Color::Black);
        int numStars = rand() % 20 + 490;
        for (int i = 0; i < numStars; i++) {
            int x = rand() % (int)width;
            int y = rand() % (int)height;
            sf::Color color(255, 255, 255, rand() % 75 + 25);
            starsImg.setPixel(x, y, color);
        }
        sf::Texture starsTexture;
        starsTexture.loadFromImage(starsImg);
        sf::Sprite stars;
        stars.setTexture(starsTexture);

        // main loop
        while (window.isOpen()) {
            if (Flags.isActive && Flags.inFocus) {
                confineCursorToWindow(window);
            } else {
                freeCursor();
            }
            sf::Event event;
            while (window.pollEvent(event)) {
                if (event.type == sf::Event::KeyPressed) {
                    if (event.key.code == sf::Keyboard::Escape) {
                        Flags.isActive = (!Flags.isActive);
                    }
                }
                if (event.type == sf::Event::MouseMoved) {
                    sprite.setPosition(event.mouseMove.x, event.mouseMove.y);
               }
                // handles default events like sf::Event::WindowClosed
                handleDefaultEventsForWindow(event, window);
            }
            window.clear();
            window.draw(stars); // here's where I draw the stars
            window.draw(sprite);
            window.display();
        }
    } catch (const char* error) {
        printf("%s\n", error);
        exit(1);
    }

    return 0;
}

编辑

我尝试加载星空的图像并尝试绘制它,游戏仍然运行缓慢!

另外,慢,我的意思是被称为“精灵”的精灵在跟随鼠标时会滞后。这真的是速度问题吗?

4

0 回答 0