【发布时间】:2015-12-19 17:24:44
【问题描述】:
我正在使用 SFML 制作游戏“Asteroids”的副本。
为了存储我所有的小行星,我使用了一个std::vector<sf::ConvexShape> 向量,它存储了所有的小行星形状。问题是从向量中绘制形状。我查看了this post,发现我可以使用迭代器来绘制我的形状(我知道他在那篇文章中使用了精灵,但我认为如果我使用形状没有区别。)
所以我尝试了:
for(std::vector<sf::ConvexShape>::iterator it=allShapes.begin();it!= allShapes.end(); ++it){
window.draw(*it);
}
这会引发异常,终止我的程序。
仅供参考:上面,allShapes 包含 sf::ConvexShape 形状。
所以问题是:如何绘制存储在矢量中的形状?
全酱:
using namespace std;
class asteroid{
public:
sf::Vector2f pos;
double angle;
void update(sf::Vector2f);
void create(std::vector<sf::ConvexShape>);
};
/* Will be implemented later
void asteroid::update(sf::Vector2f a){
pos += a;
};
*/
void asteroid::create(std::vector<sf::ConvexShape> a){
cout << "Creating..." << endl;
a.push_back(sf::ConvexShape()); //New asteroid SHAPE
std::vector<sf::ConvexShape>::iterator tempIt = a.end();
tempIt->setPointCount(4);
for(int i = 0; i < tempIt->getPointCount()+1; i++){ //Drawing asteroid
tempIt->setPoint(i, sf::Vector2f(i*100, i*100));
}
tempIt->setFillColor(sf::Color::White);
cout << "Done!" << endl;
};
int main()
{
// Init //
sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
std::vector<sf::ConvexShape> allShapes; //List of all asteroid SHAPES
std::vector<asteroid> allAsteroids; //List of asteroid CLASS OBJECTS
allAsteroids.push_back(asteroid()); //New asteroid CLASS OBJECT
for(std::vector<asteroid>::iterator it = allAsteroids.begin(); it != allAsteroids.end(); ++it){ //Creating asteroids
it->create(allShapes);
}
// Loop //
while (window.isOpen())
{
// Event //
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
// Display //
window.clear();
for(std::vector<sf::ConvexShape>::iterator it = allShapes.begin(); it != allShapes.end(); ++it){
window.draw(*it);
}
window.display();
}
return 0;
}
【问题讨论】:
-
一方面,您不能取消引用
a.end();。而且你在代码中做了一些奇怪的事情。 -
我可以通过
a.end()-1;取消引用它吗?编辑:或者更确切地说a.rbegin(); -
怪异是什么意思?
-
您通过值传递
a,而不是在asteroid::create中使用asteroid的this实例。非静态成员函数应该对对象做一些事情。 -
现在我意识到我不需要将
createvoid 作为asteroid类的成员并更改了它,现在它独立存在。另外,除了值之外,我不知道传递a的任何其他方式,这有什么不同吗?
标签: c++ vector draw sfml shape