2010-09-15 56 views
0

我嘗試做一個簡單的遊戲引擎,它由2個班,遊戲類字段重置爲零

class Game 
{ 
    protected: 
     SDL_Event event; 
     vector<Sprite> render_queue; 

     void render(); 

    public: 
     int SCREEN_WIDTH, 
      SCREEN_HEIGHT, 
      SCREEN_BPP, 
      FPS; 
     SDL_Surface *screen; 

     Game(int width, int height, int fps); 
     void reset_screen(); 
     void set_caption(string caption); 
     bool update(); 
     void quit(); 
     void add_sprite(Sprite spt); 
}; 

和雪碧

class Sprite 
{ 
    public: 
     float x,y; 
     SDL_Surface* graphics; 

     Sprite(); 
     void draw(SDL_Surface *target); 
     void loadGraphics(string path); 
}; 

當我嘗試改變精靈的x或y它在下一幀重置爲0!

的main.cpp

int main(int argc, char* args[]) 
{ 
    Game testing(640, 480, 50); 
    testing.set_caption("Test"); 

    Sprite s1; 
    Sprite s2; 

    s1.loadGraphics("img1.png"); 
    s2.loadGraphics("img1.jpg"); 

    testing.add_sprite(s1); 
    testing.add_sprite(s2); 

    while(!testing.update()) 
    { 
     s1.x = 100; 
     s2.y = 200; 
    } 

    return 0; 
} 
+1

努力幫助這裏沒有更新()和add_sprite()的代碼,以及任何他們可能會調用。 – 2010-09-15 15:39:49

回答

3

您將它們添加到Game時使精靈的副本:

class Game 
{ 
     /* ... */ 
     void add_sprite(Sprite spt); 
}; 

這就是爲什麼s1.x = 100;s2.y = 200;(在main()上不同的拷貝操作系)沒有效果。

我覺得方法應該這樣來代替定義:

class Game 
{ 
     /* ... */ 
     void add_sprite(Sprite &spt); 
}; 

這樣Game將使用從main()Sprite對象。

+0

謝謝,它的工作 – nawriuus 2010-09-15 15:54:04

0

testing.add_sprite(s2);生成sprite的副本,所以在主代碼中更改s1,s2的值對測試中的副本沒有影響。

您需要通過引用或指針傳遞給到add_sprite()