Class field resets to zero
im trying to make a simple game engine, it consists of 2 classes, Game
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);
};
and Sprite
class Sprite
{
public:
float x,y;
SDL_Surface* graphics;
Sprite();
void draw(SDL_Surface *target);
void loadGraphics(string path);
};
when im trying to change x or y of sprite it resets to 0 on next frame!
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;
}
You make copies of the sprites when adding them to the Game
:
class Game
{
/* ... */
void add_sprite(Sprite spt);
};
That's why the lines s1.x = 100;
and s2.y = 200;
(operating on a different copy in the main()
) have no effect.
I think the method should be instead defined like that:
class Game
{
/* ... */
void add_sprite(Sprite &spt);
};
That way Game
would be using the Sprite
objects from the main()
.
testing.add_sprite(s2); makes a copy of sprite, so changing the value of s1,s2 in the main code has no effect on the copy in testing.
You need to pass by reference or pointer to to add_sprite()
精彩评论