Peter
Peter

Reputation: 337

Not displaying Sprite created with class

I created a class for my pickups, in my Pickup.h. This would be:

class Pickup
{
private:
    Sprite m_Sprite;
    int m_Value;
    int m_Type;
public:
Pickup (int type)
{
    m_Type = type;
    if (m_Type == 1)
    {
        Sprite m_Sprite;
        Texture health;
        health.loadFromFile("health.png");
        m_Sprite.setTexture(health);
    }
    else ...

}
void spawn()
{
    srand((int)time(0) / m_Type);
    int x = (rand() % 1366);
    srand((int)time(0) * m_Type);
    int y = (rand() % 768);
    m_Sprite.setPosition(x, y);
}
Sprite getSprite()
{
    return m_Sprite;
}
};

If I try to draw on the screen a Sprite created with this class, using

Pickup healthPickup(1);
healthPickup.spawn();

before entering the game loop, and inside the game loop to put

    mainScreen.draw(healthPickup.getSprite());

I never get to see that Sprite on the screen. I tried to make another Sprite using

Sprite m_Sprite2;
Texture health2;
health2.loadFromFile("health.png");
m_Sprite2.setTexture(health2);
m_Sprite2.setPosition(healthPickup.getSprite().getPosition().x, healthPickup.getSprite().getPosition().y);

and if I try to display it in the game loop, everything works just fine. My question is: why this doesn't work with my created class?

Upvotes: 0

Views: 32

Answers (2)

AresCaelum
AresCaelum

Reputation: 1566

Your code should be:

class Pickup
{
private:
    Sprite m_Sprite;
    int m_Value;
    int m_Type;
public:
Pickup (int type)
{
    m_Type = type;
    if (m_Type == 1)
    {
        Texture health; // removed the declaration of m_Sprite that was here.
        health.loadFromFile("health.png");
        m_Sprite.setTexture(health);
    }
    else ...

}
void spawn()
{
    srand((int)time(0) / m_Type);
    int x = (rand() % 1366);
    srand((int)time(0) * m_Type);
    int y = (rand() % 768);
    m_Sprite.setPosition(x, y);
}
Sprite getSprite()
{
    return m_Sprite;
}
};

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409136

From the constructor:

Pickup (int type)
{
    m_Type = type;
    if (m_Type == 1)
    {
        Sprite m_Sprite;
        ...

Here you define a local variable with the same name as the member variable. This creates a local variable that will go out of scope and be destructed.

The constructor leaves the member variable uninitialized.


To solve your problem properly there are two changes you need to make: The first is to construct the member variable m_Sprite. The second is to not define the local variable.

Something like this:

Pickup (int type)
    : m_Sprite()    // Constructor initializer list, default-constructs the m_Sprite member
{
    m_Type = type;
    if (m_Type == 1)
    {
        // Don't define a local variable m_Sprite
        Texture health;
        health.loadFromFile("health.png");
        m_Sprite.setTexture(health);
    }
    ...
}

Upvotes: 2

Related Questions