SFML 2.0 - 绘制星空

时间:2012-06-18 19:48:42

标签: c++ performance optimization sfml

我正在使用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;
}

修改

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

另外,慢一点,我的意思是当跟随鼠标时,名为“精灵”的精灵会滞后。这实际上是速度问题吗?

0 个答案:

没有答案