【发布时间】:2015-05-08 02:13:19
【问题描述】:
来自官方 SFML 教程,白盒问题:-
“当你设置一个精灵的纹理时,它在内部所做的只是存储一个指向纹理实例的指针。因此,如果纹理被破坏或移动到内存中的其他地方,精灵最终会得到一个无效的纹理指针。”因此将看到一个没有纹理的精灵。
我有一个名为 World 的课程。在这个类中,我创建了一个名为 level 的二维整数数组和一个名为 Block 的 Block 类型的向量。现在我想在 level[ i ][ j ] = 1 时将“块”对象存储在向量中。
'World' 类的头文件:-
#ifndef WORLD_H
#define WORLD_H
#include <vector>
#include "Block.h"
#include "Grass.h"
#include <SFML/Graphics.hpp>
using namespace std;
class World
{
public:
World();
void draw(sf::RenderWindow *window);
vector<Block> blocks;
private:
int level[12][16];
int wd;
int hi;
};
#endif // WORLD_H
'World' 类的 cpp 文件 :-
#include "World.h"
#include "Grass.h"
#include "Block.h"
#include <iostream>
#include <SFML/Graphics.hpp>
using namespace std;
World::World() : level{
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1},
{1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1},
{1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1},
{1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
}
{
wd = 16;
hi = 12;
int count = 1;
//make a 'Block' object and pass it in the vector when level[ i ][ j ] = 1.
for(int i = 0; i<hi; i++)
{
for(int j = 0; j<wd; j++)
{
if(level[i][j] == 1)
{
Block block(j*50, i*50);
blocks.push_back(block);
}
}
}
}
void World::draw(sf::RenderWindow *window)
{
for(unsigned int i = 0; i<blocks.size(); i++)
{
blocks[i].draw(window);
}
}
'Block' 类有两个成员 - sf::Texture blockT 和 sf::Sprite block。它还有一个 draw(RenderWindow *window) 方法。这就是“块”类的制作方式:-
块类的头文件
#ifndef BLOCK_H
#define BLOCK_H
#include <iostream>
#include <SFML/Graphics.hpp>
using namespace std;
class Block
{
public:
Block(float x, float y);
void draw(sf::RenderWindow *window);
private:
sf::Texture blockT;
sf::Sprite block;
};
#endif // BLOCK_H
'Block' 类的 cpp 文件
#include "Block.h"
#include <iostream>
#include <SFML/Graphics.hpp>
using namespace std;
Block::Block(float px, float py)
{
if(!(blockT.loadFromFile("textures/block.png")))
{
cout<<"Could not load block texture."<<endl;
}
block.setTexture(blockT);
block.setPosition(sf::Vector2f(px, py));
cout<<px<<endl;
cout<<py<<endl;
}
void Block::draw(sf::RenderWindow *window)
{
window->draw(block);
}
当我运行程序时,代替块,只显示白框。我不明白纹理是如何被破坏的。这就是输出的样子:-
如您所见,白色的地方是大小为 50*50 的精灵,没有任何纹理。
【问题讨论】:
-
你应该更加小心使用命名空间,尤其是在头文件中! :) 见stackoverflow.com/a/5849668/781978
标签: c++ vector textures sprite sfml