这是一个创建鸡入侵者游戏的代码,当我刚刚初始化一只鸡时,游戏(或者我可以做的任何游戏部分)工作得很好,但是当我把它变成一个2d的鸡群时它给我看了这个错误。
RenderWindow window;
int main(int, char const**)
{
chicken chick[4][7];
Sprite back;
Clock clock;
window.create(VideoMode(1800, 1000), "Menu");
while (window.isOpen())
{
Event event;
while (window.pollEvent(event))
{
if (event.type == Event::KeyPressed && event.key.code == Keyboard::Escape)
window.close();
if (event.type == Event::Closed)
window.close();
}
Texture texture;
if (!texture.loadFromFile(resourcePath() + "background.jpg"))
{
std::cout << "Error loading texture" << std::endl;
}
Time time;
time = clock.getElapsedTime();
if (time.asSeconds() >= 0.001)
{
chick[4][7].handle(window, clock);
clock.restart();
}
window.clear();
back.setTexture(texture);
back.setPosition(0, 0);
back.setTextureRect(IntRect(0, 0, 1800, 1000));
window.draw(back);
for (int i = 0; i < 4; i++)
for (int j = 0; j < 7; j++)
chick[i][j].initialize(window);
window.display();
}
}
///////////////////
this is the app file for the chicken class
using namespace sf;
class chicken
{
private:
RectangleShape chick;
bool flag;
public:
chicken();
void initialize(RenderWindow &window);
void handle(RenderWindow & window, Clock clock);
~chicken();
};
#endif /* chicken_hpp */
/////////////////////////////////////////////////////////////
this is the cpp file for the chicken class
using namespace sf;
chicken::chicken()
{
chick.setPosition(500, 500);
chick.setSize(Vector2f(200, 200));
chick.setOrigin(100, 100);
flag = true;
}
void chicken::initialize(RenderWindow & window)
{
Texture texture2;
if (!texture2.loadFromFile(resourcePath() + "chicken3.jpg"))
{
std::cout << "Error loading texture" << std::endl;
}
chick.setTexture(&texture2);
window.draw(chick);
}
void chicken::handle(RenderWindow & window, Clock clock)
{
if (flag) //the error appears here
{
chick.move( 10 , 0 ) ;
}
else
{
chick.move(-10 , 0);
}
if (chick.getPosition().x >= window.getSize().x)
flag = false;
if(chick.getPosition().x < 0)
flag = true;
}
chicken::~chicken()
{
}
答案 0 :(得分:0)
将来请在您的问题中包含整个错误消息,但是这里的问题是您正在访问鸡阵列中的越界索引。
你的数组大小是4x7,这意味着你的有效索引是0 - 3和0 - 6。
你的手柄功能正在小鸡[4] [7]上调用,这是超出界限的。
如果你试图只在数组中的最后一个小鸡上调用该函数,那么
chick[3][6].handle(window, clock);
在每只鸡上调用它,你需要一个双循环,如
for(int i = 0; i < 4; ++i)
{
for(int j = 0; j < 7; ++j)
{
chick[i][j].handle(window, clock);
}
}