【问题标题】:Why does my SFML keep crashing when passing sf::Texture as an argument into a function为什么我的 SFML 在将 sf::Texture 作为参数传递给函数时不断崩溃
【发布时间】:2019-05-06 21:09:01
【问题描述】:

当我尝试将纹理作为参数传递给函数,然后运行程序时,我一运行就在窗口上收到“Program.exe 已停止工作”消息.

我可以在函数内部创建纹理,然后它会运行,但是这会破坏函数末尾的纹理,所以我得到的只是一个白框。

void create_sprite(sf::Texture texty, float lenScale, float widScale, int houseNum, int fieldNum){
    sf::Sprite* spritey = new sf::Sprite(texty);
    spritey -> setScale(lenScale, widScale);
    spritey -> setPosition(fieldWidCoor[houseNum-1][fieldNum-1], fieldLenCoor[houseNum-1][fieldNum-1]);
    houseList.push_back(*spritey);
}

Then in main{}

    sf::Texture grassTex;
    grassTex.loadFromFile("images/field-grass.png");
    create_sprite(grassTex, 0.2, 0.3, 1, 1);


It should cause all calls to the function to create another sprite with the same Texture, but all I get is the crash.

【问题讨论】:

  • 重要的是要注意 sf::Sprite 实例不会复制它使用的纹理,它只保留对它的引用。因此,当 sf::Sprite 使用 sf::Texture 时,不得破坏它。来自 sfml 参考。
  • 你也永远不会检查纹理是否已经加载
  • 如果您只是要将精灵复制到矢量中,则不应在那里动态创建精灵。只需将其声明为局部变量:sf::Sprite spritey(texty); 甚至使用 emplacehouseList.emplace_back(texty);
  • 我正在动态创建它,因为我将使用相同的纹理创建相当多的精灵,我不想一个一个地初始化它们。

标签: c++ sfml


【解决方案1】:

基本上,sf::Sprite 实例保留了对其使用的纹理的引用。因此,当 sf::Sprite 使用 sf::Texture 时,它​​不能被破坏,这是您尝试执行的操作并导致错误。

【讨论】:

    猜你喜欢
    • 2021-05-29
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 2013-01-27
    • 2020-01-16
    • 1970-01-01
    相关资源
    最近更新 更多