【发布时间】: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);甚至使用 emplace:houseList.emplace_back(texty); -
我正在动态创建它,因为我将使用相同的纹理创建相当多的精灵,我不想一个一个地初始化它们。