SFML community forums

Help => Graphics => Topic started by: carton83 on May 05, 2014, 05:37:32 am

Title: I have a referenced sprite that I can't change the position of
Post by: carton83 on May 05, 2014, 05:37:32 am
I know from debugging that the in function sprite's position data does correctly change but this is not reflected main version of said sprite.  This is also despite the fact that both sprites do indeed share the same address.

I have to be missing something.

This tiny bit of code is fairly simple.  If you hit the A key the sprite is suppose to move down and right by 10px. But it doesn't.  No idea why.

#include <SFML/Graphics.hpp>

class Test
{
    public:
    Test(sf::Sprite &tempTestSprite)
    {
        testSprite = tempTestSprite;
    }

    sf::Sprite testSprite;

    void Blah();
};

void Test::Blah()
{
    testSprite.setPosition(testSprite.getPosition().x+10, testSprite.getPosition().y+10);
}

int main()
{
    sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");

    sf::Texture texture;
    if(!texture.loadFromFile("cb.bmp"))
    {
        return -1;
    }

    sf::Sprite logo(texture);

    Test tester(logo);

        while(window.isOpen())
    {

        // Process events
        sf::Event event;
        while(window.pollEvent(event))
        {
            switch(event.type)
            {
                case sf::Event::KeyPressed:
                {
                    // Close window : exit
                    if(event.key.code == sf::Keyboard::Escape)
                    {
                        window.close();
                    }
                    if(event.key.code == sf::Keyboard::A)
                    {
                        tester.Blah();
                    }
                }
            }
        }



        window.clear();
        window.draw(logo);
        window.display();

    }

    return 0;
}
Title: Re: I have a referenced sprite that I can't change the position of
Post by: G. on May 05, 2014, 06:01:49 am
This is also despite the fact that both sprites do indeed share the same address.
I highly doubt that...
testSprite and logo are 2 different sprites. You move testSprite, and you draw logo...

Could work like this:
class Test
{
    public:
    Test(sf::Sprite &tempTestSprite) : testSprite(tempTestSprite)
    {
    }

    sf::Sprite& testSprite;

    void Blah();
};
Title: Re: I have a referenced sprite that I can't change the position of
Post by: carton83 on May 05, 2014, 06:48:21 am
And this is why I ask questions.  So I need an initialization list, huh?  Thanks.
Title: Re: I have a referenced sprite that I can't change the position of
Post by: Jesper Juhl on May 05, 2014, 07:00:08 am
And this is why I ask questions.  So I need an initialization list, huh?  Thanks.
What you really needed was to store a reference instead of a copy.