我的 renderwndow 变成空白并停止工作
My renderwndow becomes blank and stops working
实际上我正在尝试制作子弹射击 code.I 使用矢量并将精灵添加到其中,并且在我 运行 我的程序我的 [=17] 中将位置分开 vectors.But =] 停止 working.Here 是 code.I 希望它不再重复。
#include <SFML/Graphics.hpp>
#include <iostream>
#import "bulletcode.h";
#include <vector>
using namespace std;
using namespace sf;
int main()
{
vector<Sprite> bullets;
vector<float> xp;
vector<float> yp;
sf::RenderWindow window(sf::VideoMode(900, 600), "SFML works!");
sf::CircleShape shape(75.f);
shape.setFillColor(sf::Color::Green);
Texture bullet;
bullet.loadFromFile("bullet.png");
shape.setPosition(400,100);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
if(Keyboard::isKeyPressed(Keyboard::Space)){
Sprite bulletsp;
bulletsp.setTexture(bullet);
bulletsp.setScale(0.8,0.8);
bullets.push_back(bulletsp);
xp.push_back(shape.getPosition().x);
yp.push_back(shape.getPosition().y);
}
for(int i=0;i<=bullets.size()-1;i=i){
yp[i]=yp[i]+0.2;
i++;
bullets[i].setPosition(xp[i],yp[i]);
window.draw(bullets[i]);
}
window.clear();
window.draw(shape);
window.display();
}
return 0;
}
你在循环中递增 i。因此,在最后一次迭代中,您将访问数组的末尾。
您可能希望将循环声明中的 i=i
替换为 i++
,而不是在循环体中递增 i。
由于 for 循环,您的程序无法运行:
for(int i=0;i<=bullets.size()-1;i=i)
其中 bullets.size()
是 size_t (unsigned int)
。当您的项目符号向量为空 (size() = 0
) 时,条件 i=0 <= (unsigned int)(0 - 1)
始终为真。你的程序进入for body就崩溃了(yp,xp,bullets都是空的)
你的编译器应该在某个地方警告你这个问题?
您应该使用 for(size_t i=0;i < bullets.size(); i++ )
并修改您的正文代码,这可以使您的代码保持整洁并避免问题的根源。
实际上我正在尝试制作子弹射击 code.I 使用矢量并将精灵添加到其中,并且在我 运行 我的程序我的 [=17] 中将位置分开 vectors.But =] 停止 working.Here 是 code.I 希望它不再重复。
#include <SFML/Graphics.hpp>
#include <iostream>
#import "bulletcode.h";
#include <vector>
using namespace std;
using namespace sf;
int main()
{
vector<Sprite> bullets;
vector<float> xp;
vector<float> yp;
sf::RenderWindow window(sf::VideoMode(900, 600), "SFML works!");
sf::CircleShape shape(75.f);
shape.setFillColor(sf::Color::Green);
Texture bullet;
bullet.loadFromFile("bullet.png");
shape.setPosition(400,100);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
if(Keyboard::isKeyPressed(Keyboard::Space)){
Sprite bulletsp;
bulletsp.setTexture(bullet);
bulletsp.setScale(0.8,0.8);
bullets.push_back(bulletsp);
xp.push_back(shape.getPosition().x);
yp.push_back(shape.getPosition().y);
}
for(int i=0;i<=bullets.size()-1;i=i){
yp[i]=yp[i]+0.2;
i++;
bullets[i].setPosition(xp[i],yp[i]);
window.draw(bullets[i]);
}
window.clear();
window.draw(shape);
window.display();
}
return 0;
}
你在循环中递增 i。因此,在最后一次迭代中,您将访问数组的末尾。
您可能希望将循环声明中的 i=i
替换为 i++
,而不是在循环体中递增 i。
由于 for 循环,您的程序无法运行:
for(int i=0;i<=bullets.size()-1;i=i)
其中 bullets.size()
是 size_t (unsigned int)
。当您的项目符号向量为空 (size() = 0
) 时,条件 i=0 <= (unsigned int)(0 - 1)
始终为真。你的程序进入for body就崩溃了(yp,xp,bullets都是空的)
你的编译器应该在某个地方警告你这个问题?
您应该使用 for(size_t i=0;i < bullets.size(); i++ )
并修改您的正文代码,这可以使您的代码保持整洁并避免问题的根源。