Aerdenhein
Aerdenhein

Reputation: 3

Sprite isn't moving

I'm new to programming and, since I find it easier to learn doing, I was playing around with C++ and SFML. I was trying to get a sprite to move, but for some reason, I can't do it. I've tried everything I found, but no luck. Anyone know why this isn't working? I'm using Visual Studio 2012 Express and SFML 2.1, by the way.

int main()
{
    sf::RenderWindow window(sf::VideoMode(1000, 800), "Project");
    window.setFramerateLimit(30);
    glEnable(GL_TEXTURE_2D);
    window.clear(sf::Color::White);
    window.display();
    sf::Texture charMain;
    if (!charMain.loadFromFile("Images/playerFrontSprite.png"))
    {
        return 1;
    }
    sf::Sprite charaMain;
    charaMain.setPosition(500.f , 500.f);
    charaMain.setTexture(charMain);
    window.draw(charaMain);
    window.display();
    sf::Font cavefont;
    sf::Font::Font(cavefont);
    if (!cavefont.loadFromFile("Cave-Story.ttf"))
        return 1;
        while (window.isOpen())
        {
            sf::Event playerAction;
            while (window.pollEvent(playerAction))
            {
                switch(playerAction.type)
                {
                case sf::Event::Closed:
                    window.close();
                    break;
                case sf::Event::KeyPressed:
                    std::cout << "sf::Event::KeyPressed" << std::endl;
                    switch(playerAction.key.code)
                    {
                    case sf::Keyboard::W:
                        charaMain.move(0 , 1);
                        break;
                    case sf::Keyboard::A:
                        charaMain.move(-1 , 0);
                        break;
                    case sf::Keyboard::S:
                        charaMain.move(0 , -1);
                        break;
                    case sf::Keyboard::D:
                        charaMain.move(1 , 0);
                        break;
                    }
                    break;
                }
            }
            }
}

Upvotes: 0

Views: 282

Answers (1)

Kylotan
Kylotan

Reputation: 18449

Your problem is that you're moving the object, but you're not drawing it on the screen at its new position. Your drawing code is outside the main loop, so it never gets called after you move the sprite, so you never see the effects.

You basically need to pull the rendering code (ie. window.draw(charaMain) and window.display()) inside the while (window.isOpen()) loop, outside the event handling loop.

Upvotes: 3

Related Questions