我的档案中有这个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)的文章,并添加了带有纹理的新矢量。我的代码现在看起来像这样:
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]);
然后它再次崩溃!
---更新:现在,我再次更改了代码,没有崩溃,但是我的纹理是白色正方形。我的纹理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++)
或类似的东西。
另外,希望您在某个时候初始化精灵。在调用load()之前,您需要用Sprites(用sprites.push_back(mySprite)之类的东西)填充矢量。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句