数组/向量中的SFML 2.0 c精灵
我在我的文件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]); } }; 我没有错误,但我的游戏崩溃了.我想,问题在于读取sprite [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; —-更新: 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))填充向量. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |