0
\$\begingroup\$

I am making a small game in LibGDX and it all works, sprites are moving etc. The drawing is mainly done in the render() method of a Screen, using Batch.draw(TextureRegion). So far so good.

But now I would like my sprites to rotate. There are Batch draw methods for rotation (I think), but I noticed a bunch of useful methods in tne Sprite class. Problem is I do not know how to use them without making the rest of the program ugly.

I could have a Sprite as a member of each "game object", but that makes direct dependency of the game model on drawing mechanism, specifically LibGDX. Besides I can see problems with serialization and duplicate parameters (Sprite x,y vs model x,y etc) and unnecessary overhead.

Or I could subclass Sprite, which would probably be orders of magnitude messier.

Is there a common way of clearly separating the model part and rendering part of a small game? And how is Sprite typically used?

\$\endgroup\$
0
\$\begingroup\$

The Sprite class is just that. A Sprite. It represents a texture in 2D space that can be transformed (moved, rotated, scaled) however you like. Think of it as a more sophisticated Texture (or TextureRegion) class that is used in the same way.

Your characters should probably not extend Sprite since your characters aren't sprites, they have sprites. Hence your character class would contain a Sprite not extend from it.

A minimalistic character class might look something like this:

public class Character {
    private float x, y; //Position
    private Sprite sprite;

    public void update() {
        // Before this update character velocity, position, etc...
        sprite.setPosition(this.x, this.y);
    }

    public void draw(Batch batch) {
        // This is how you draw a sprite.
        sprite.draw(batch);
    }
}

As for unnecessary overhead and serialization etc. you shouldn't worry. Premature optimization like that is the bane to everyone's existence. But you should never serialize textures of any kind anyways so you should probably make your sprite field transient (see this question if you don't know what transient is).

\$\endgroup\$
  • \$\begingroup\$ Yes, this is the approach that first came to mind. It is not too good, but the only other solution I can see is a Drawer class for each type of character and I think java is too verbose for that. The objections are just examples of how bad this design is, not premature optimization. And yes, I know what transient is:) \$\endgroup\$ – comodoro Jun 24 '17 at 7:58
  • \$\begingroup\$ I am accepting the answer because no other appeared and because this is what I am doing now. Separate drawing classes may come in later though. \$\endgroup\$ – comodoro Jul 5 '17 at 7:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.