2017-01-04 8 views
0
創建的Sprite

我在Pickup.h中爲我的拾音器創建了一個類。 這將是:不顯示用類

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; 
} 
}; 

如果我試着畫出這個類創建的屏幕雪碧上,使用

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

進入遊戲循環之前,和遊戲圈裏面放

mainScreen.draw(healthPickup.getSprite()); 

我永遠不會在屏幕上看到Sprite。我試圖讓另一個雪碧使用

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

如果我嘗試在遊戲循環中顯示它,一切正常。我的問題是:爲什麼這不適用於我創建的類?

+1

NVM看看你的構造函數,你正在創建一個名爲只需設置你的m_sprite m_sprite代替精靈。 – Eddge

回答

1

你的代碼應該是:

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; 
} 
}; 
2

從構造:

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

在這裏定義一個局部變量具有相同名稱的成員變量。這會創建一個局部變量,它將超出範圍並被破壞。

該構造函數保留未初始化的成員變量。


解決您的問題正確有你需要兩個變化:首先是構建成員變量m_Sprite。其次是不定義局部變量。

事情是這樣的:

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); 
    } 
    ... 
}