在我的SFML应用程序中,我自己的移动功能无法正常工作。如果我直接将代码编写到主函数中,它将正常工作。
我的目标是根据坐标和给定的路标移动和旋转汽车。
路是:
[每个路标均为239 * 239,汽车的起步高度为150 * 150。
我的移动功能是:
void Vehicle::move(int increment, int increment2, float &ax, float &ay, sf::Sprite &mySprite)
{
ax += increment;
ay += increment2;
if(ax == 150 && ay == 150)
{
mySprite.setRotation(0);
increment = 1;
increment2 = 0;
}
else if((ax == 239*2 + 90) && ay == 150)
{
mySprite.setRotation(90);
increment = 0;
increment2 = 1;
}
else if((ax == 239*2 + 90) && ay == 239*2 + 150)
{
mySprite.setRotation(0);
increment = 1;
increment2 = 0;
}
else if((ax == 239*4 + 90) && ay == 239*2 + 150)
{
mySprite.setRotation(90);
increment = 0;
increment2 = 1;
}
else if((ax == 239*4 + 90) && ay == 239*4 + 90)
{
mySprite.setRotation(180);
increment = -1;
increment2 = 0;
}
else if((ax == 150) && ay == 239*4 + 90)
{
mySprite.setRotation(270);
increment = 0;
increment2 = -1;
}
}
我的主要功能是:
float x = 150.f;
float y = 150.f;
float angle = 0.f;
int increment = 1;
int increment2 = 0;
sf::RenderWindow renderWindow(sf::VideoMode(1200, 1200), "Traffic Simulator");
tVehicleType myVehicleType = VEHICLE5;
sf::Sprite mySprite;
sf::Texture myTexture;
Vehicle *myVehicle;
myVehicle = new Vehicle(myVehicleType, x, y, angle, mySprite, myTexture);
sf::FloatRect boundingBox = mySprite.getGlobalBounds();
mySprite.setOrigin(sf::Vector2f(boundingBox.width / 2, boundingBox.height / 2));
while (renderWindow.isOpen())
{
sf::Event event;
while(renderWindow.pollEvent(event))
{
if (event.type == sf::Event::Closed)
renderWindow.close();
}
mySprite.setPosition(x, y);
renderWindow.clear(sf::Color::White);
renderWindow.draw(mySprite);
renderWindow.display();
myVehicle->move(increment, increment2, x, y, mySprite);
如果我这样编写代码,则此代码将无法正常工作,而我必须这样编写。如果我直接将move函数写入主代码的最后一行,则可以正常工作。
我该如何解决这个问题?