簡體   English   中英

SFML 2.0 - 用精靈矢量繪圖

[英]SFML 2.0 – drawing with vector of sprites

我正在嘗試創建一個循環來在屏幕上繪制10個塊,但沒有顯示任何內容。 我沒有錯誤,所以我認為向量不存儲sprite。 我是SFML的新手,所以我真的不知道自己做錯了什么。

sf::Texture bTexture;
sf::Texture bloqueTexture;
sf::Sprite bloqueSprite;

//create vector of blocks
std::vector<sf::Sprite> bricks(10, sf::Sprite(bloqueTexture));

fondo.setTexture(img_mgr.getImage("fondo.jpg"));
personaje.setTexture(img_mgr.getImage("jumper.png"));
personaje.setPosition(100,POSICION_TERRENO_Y);
bloqueSprite.setTexture(img_mgr.getImage("bloque.png"));
bloqueTexture.loadFromFile("Recursos/imagenes/bloque.png");

//Fill the vector with the texture
for (int i = 0; i < bricks.size(); i++)
{
    bricks[i].setTexture(bloqueTexture);
    bricks[i].setPosition(100 + (i * 45) , 320);
    window.draw(bricks[i]);
}

我認為問題是加載紋理,嘗試檢查loadFromFile函數返回true。

第二次編輯並給出最終答案:如果要使用SFML顯示png文件,請將它們保存為8位。

編輯:我在第二個代碼中有一些不好的復制/粘貼,我修復了它

由於SFML是針對多媒體應用程序(主要是游戲)而制作的,因此您需要frames刷新並繪制多次屏幕(即frames )。 話雖這么說,基本的方法是讓主循環做三件事:處理輸入,更新游戲邏輯然后繪圖。

請參閱SFML網站上的經典示例:

#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw(shape);
        window.display();
    }

    return 0;
}

你的紋理加載和填充矢量必須在主循環之前完成,然后在window.clear()window.display你需要繪制你想要顯示的所有內容(你的塊)。

你最終會得到這樣的東西:

#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");

    sf::Texture bTexture;
    sf::Texture bloqueTexture;
    sf::Sprite bloqueSprite;

    //create vector of blocks
    std::vector<sf::Sprite> bricks(10, sf::Sprite(bloqueTexture));

    fondo.setTexture(img_mgr.getImage("fondo.jpg"));
    personaje.setTexture(img_mgr.getImage("jumper.png"));
    personaje.setPosition(100,POSICION_TERRENO_Y);
    bloqueSprite.setTexture(img_mgr.getImage("bloque.png"));
    bloqueTexture.loadFromFile("Recursos/imagenes/bloque.png");

    for (int i = 0; i < bricks.size(); i++)
    {
        bricks[i].setTexture(bloqueTexture);
        bricks[i].setPosition(100 + (i * 45) , 320);
    }

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        for (int i = 0; i < bricks.size(); i++)
        {
            window.draw(bricks[i];
        }
        // Consider doing this :
        // for(const auto& brick : bricks)
        //    window.draw(brick);

        window.display();

    }

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM