gpt4 book ai didi

c++ - 数组/vector 中的 SFML 2.0 c++ Sprite

转载 作者:太空狗 更新时间:2023-10-29 20:13:27 25 4
gpt4 key购买 nike

我的文件 blocks.h 中有这个:

  #include <vector>
class Blocks{
public:
string files_name[4];
vector < Sprite > sprites;
void load(){
for(int i=0;i<=sizeof(files_name);i++){
Texture my_texture;
my_texture.loadFromFile(this->files_name[i]);
sprites[i].setTexture( my_texture );

}
}
Blocks(){
this->files_name[0] = "wall.png";
this->files_name[1] = "floor.png";
this->files_name[2] = "live.png";
this->files_name[3] = "coins.png";
this->load();
}
void show(int id, int X, int Y){
sprites[id].setPosition(X, Y);
window.draw(sprites[id]);
}
};

我没有错误,但我的游戏崩溃了。我认为,问题在于读取 sprites[i].setTexture(...)

的行

我只有消息:进程终止,状态为 -1073741819(0 分 2 秒)

我的 IDE 是 Code::Blocks 10.05,我有 Windows 8。

当然,在文件main.cpp中,我定义了窗口:

RenderWindow window( VideoMode(920, 640, 32 ), "Game" );

#include "blocks.h"
Blocks BLOCKS;

----更新:好的,现在它没有崩溃,谢谢!但是,现在我看不到纹理了!我阅读了 Benjamin Lindley 的帖子,并添加了一个带有纹理的新 vector 。我的代码现在看起来像这样:

const int arraySize = 4; 
string files_name[4];
vector < Sprite > sprites;
vector < Texture > textures;

并且,在 load() 中,我有:

for(int i = 0; i < arraySize; i++){ 
Texture new_texture;
new_texture.loadFromFile(this->files_name[i]);
textures.push_back(new_texture);
sprites[i].setTexture(textures[i]);

然后它又崩溃了!

---更新:现在我再次更改了我的代码并且没有崩溃,但我的纹理是white squares .我的纹理 live.png 有效,但其他纹理是白色的!这是我的新代码:

    Sprite new_sprite;
new_sprite.setTexture(textures[i]);
sprites.push_back(new_sprite);

最佳答案

问题是这一行:

for(int i=0;i<=sizeof(files_name);i++){

如果你打印出sizeof(files_name)的值,你会发现它是16,而不是4!不要在这里使用 sizeof。另外,不要在此处使用 <=,因为即使您将 sizeof(files_name) 替换为 4,您也会尝试访问 files_name[4],这也会给您带来错误。

相反,您可以使用:

const int arraySize = 4;
string files_name[arraySize];
...
for(int i = 0; i < arraySize; i++)

或类似的东西。

此外,希望您在某个时候初始化 Sprite 。在调用 load() 之前,您需要使用 Sprites(使用类似 sprites.push_back(mySprite) 的东西)填充 vector 。

关于c++ - 数组/vector 中的 SFML 2.0 c++ Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21345696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com