OK, so I was creating a game which was going just fine, until I encountered a very strange problem.
My project uses Box2D and SFML, which has always given beginners loads of trouble, but I am not exactly a beginner. In my project, I have a component based architecture and then a player class which binds everything together. The problem is, that my sprite does not follow the position of it's body. It goes where it is supposed to be but then does not move. This might be a bit confusing, but everything will be clearer later on. This is my main code:
#include <iostream>
#include <SFML/Graphics.hpp>
#include <Box2D/Box2D.h>
#include "Player.h"
using namespace std;
int main()
{
sf::RenderWindow *window = new sf::RenderWindow(sf::VideoMode(800, 600, 32), "Quanta");
sf::FloatRect viewRect(0, 0, 800/50, 600/50);
sf::View gameView(viewRect);
b2Vec2 gravity(0.0f, -10.0f);
b2World *world = new b2World(gravity);
Player mainPlayer(*window, *world);
sf::RectangleShape testShape;
testShape.setFillColor(sf::Color(0, 0, 0));
testShape.setSize(sf::Vector2f(1.28, 1.28));
while(window->isOpen())
{
sf::Event ev;
while(window->pollEvent(ev))
{
if(ev.type == sf::Event::Closed || sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
window->close();
}
window->clear(sf::Color(100, 175, 255));
world->Step(1.0f/60.0f, 6, 2);
window->setView(gameView);
mainPlayer.UpdatePlayer(*window);
//window->draw(testShape); //This is required, you'll see why later on.
window->display();
}
delete window;
delete world;
return 0;
}
And this is the code from UpdatePlayer():
void Player::UpdatePlayer(sf::RenderWindow& window)
{
b2Vec2 bodyPosition = _playerBody.body->GetPosition();
sf::Vector2f spritePosition(bodyPosition.x, bodyPosition.y);
sf::Vector2u spriteSize(1.28f, 1.28f);
_renderPlayer.UpdateSprite(window, playerSprite, spritePosition, spriteSize); //Graphics component will update the sprite
}
And from UpdateSprite():
void GraphicsComponent::UpdateSprite(sf::RenderWindow& window, sf::Sprite &objectSprite, sf::Vector2f positions,
sf::Vector2u objectSize)
{
objectSprite.setPosition(positions.x - (objectSize.x / 2), -(positions.y + (objectSize.y /2)));
window.draw(objectSprite);
}
Now, this used to work in SFML 1.6, but now, the sprite does not fall. It just stays at the position at which it's Box2D body was initialized. To see what was going on, I outputted the position of the Box2D body and it shows that the body is moving. However, the sprite is not following it's position.
BUT, if I uncomment the line which says "window->draw(testShape)" , then the sprite falls! This means, that the sprite updates it's position only when there is something else being drawn to the screen as well! I don't know if this is supposed to happen, but it didn't in SFML 1.6 so I am now very confused.