Game objects in a 2D game - sprites that contain sprites or sprites and scenes?

Started by
7 comments, last by futlib 11 years, 6 months ago
I'm running into some design issues with the 2D game I'm currently working on.

My current object hierarchy is like this:

  • Sprite

    • Image
    • Label
    • Button (uses Image and Label by composition)


As you might guess, most of my game is UI. I also have a Scene class that owns a couple of sprites and draws them, forwards user input to them etc.

The problem is: The case of sprites including other sprites (like Button) is getting more common, and a scene is basically also a sprite containing other sprites. Would it make sense to have nothing but sprites here, and make it possible to nest them arbitrarily? Or should I keep the distinction between scene and sprite? In the latter case, how would I be able to reuse the code for drawing and forwarding input to all children of a sprite?
Advertisement
Scene isnt really a sprite because it doesnt contain image data in itself...

How i think you should do it unless you find a better solution:

-Sprite
*Linear container of sprites (so sprites have child sprites)

*Linear container of stuff affecting the rendering (image?)
*Linear container of stuff that needs to get input (button)
(you might not need a linear container, which is like vector or similiar, for all of those, or you might put the images and buttons in the same, whichever works the best)

-Image,Button etc.
*Cannot have sprites or other buttons or images as children

So you get a tree like

*Sprite
*Sprite
Image
*Sprite
Button
Image
*Sprite
*Sprite
Button
Image
*Sprite
Image

Which you store the root node for in a Scene object. The scene object can give you methods and such which modify the whole tree or get you data about it or possibly handle the allocation and building of it.

I believe this is called a scene-graph or is similiar to it.

Because the sprites dont in this way need to contain an image, i wouldnt call them sprites but find a better name for them.

If you make a rule that a sprite may not go outside the edges of its parent or get input from there, you can do rendering hierarchially, and input in the same way (for each sprite, check wether the mouse is on top, and if yes, do the same for its children. If the sprite is a button you can pass input information depeding on rules you make like allowing input to sprites covered by other sprites etc.)

I put the rendering affecting components in a different container than others in the example because that way when rendering you can get all of those components of the sprite, and for each call something like .Draw(spriteItsContainedIn) to draw the image or text on it...

[edit]
Something like:
*ObjectContainer
*Area (member)
*Sprite (component)
*Image (member)
*Button (component)

might be better, where the tree is a tree of objectcontainers, and sprite has an image property/component

I believe this is called or is similiar to a SceneGraph and might have something to do with component based design (or whatever the term is)

o3o

Your problem is that you're abusing inheritance. You should favor composition over inheritance unless you have reason to do otherwise. You don't have true IS-A relationships in your hierarchy. Button is not a Sprite, it just contains a sprite. Likewise for Label and Scene. These are all things that CONTAIN sprites, and if your hierarchy were flattened to reflect that truth, you wouldn't have a problem with button, or anything else, containing any arbitrary number of sprites.


In the latter case, how would I be able to reuse the code for drawing and forwarding input to all children of a sprite?


Sprite shouldn't have children. Sprite is sprite, it's singular. It also does not have means for collecting input--that's far beyond its purview. What you may want instead is some base-class GUIElement. This class could provide default implementations for listening to and forwarding input, as well as adding and removing children. The classes that you derive from GUIElement can hold as many sprites as is appropriate for whatever particular element they are representing.

Between Scylla and Charybdis: First Look <-- The game I'm working on

Object-Oriented Programming Sucks <-- The kind of thing I say


How i think you should do it unless you find a better solution:

So you're suggesting I have a couple of concrete UI elements like Button and Image that use sprites (or what I would call them in the future) by composition? The problem is that Image is a pretty basic thing, actually used by Button right now. I've got more complicated UI elements that include multiple buttons, images and labels.
Regarding the scene graph, I think my approach basically works like that already, so I guess that's good smile.png



Sprite is sprite, it's singular. It also does not have means for collecting input--that's far beyond its purview. What you may want instead is some base-class GUIElement. This class could provide default implementations for listening to and forwarding input, as well as adding and removing children. The classes that you derive from GUIElement can hold as many sprites as is appropriate for whatever particular element they are representing.


But what _is_ a sprite then? A visual representation of an entity? A "drawable"? I have so far been using the term synonymous for "entity", actually.

You're right, I could just rename Sprite to Widget and my object hierarchy would suddenly make sense. In Qt for example, widgets can be nested. But I just thought it felt wrong to call it Widget, since I'm after all working on a game here... There is a lot of UI, but there's more, and I don't want the UI to dominate the terminology in my code base. When I add characters moving around, they would probably end up deriving from Widget...

Then again, I guess I don't need to have my individual entities handle input like widgets would, my past games usually had per-scene input handling. I think I'm mainly struggling with how I can have my UI (screens and widgets) fit into the same object system as my entities and scenes. My initial approach was to opt for less UI-typical code and use entities and scenes for the UI instead. But one thing that was particularly annoying was central input handling...

You're right, I could just rename Sprite to Widget and my object hierarchy would suddenly make sense. In Qt for example, widgets can be nested. But I just thought it felt wrong to call it Widget, since I'm after all working on a game here... There is a lot of UI, but there's more, and I don't want the UI to dominate the terminology in my code base. When I add characters moving around, they would probably end up deriving from Widget...


What is a Widget? What inextricable properties does Widget possess? If it's synonymous with Entity, like Sprite was, then the answer is probably "nothing." A Widget on its own carries no inherent properties. You're almost always going to end up having an invisible Widget, or a Widget that doesn't care about input, or that can't move, or has no position, or has a position in 2-space instead of 3-space, etc. etc. To me, this just says that trying to fit your game objects into a hierarchy is a bad idea, they're not concrete enough. That's why the component based approach has caught on so well, it fits the problem space much better than a more vanilla approach to OOP.

If you broke your current mental concept of Widget out into a class that could be contained and used by any game "Entity", then you could share the provided functionality between both typical "game entities" and GUI elements with none of the troubles of making this work via inheritance. For instance, an in game character and a button could both be Entities that contain a "Clickable" or "Inputtable" component. Some InputDispatcher class is aware of these components, and dispatches input events to them, possibly after filtering the input into some nice format or sending only events that a particular component has said that its interested in.


I think I'm mainly struggling with how I can have my UI (screens and widgets) fit into the same object system as my entities and scenes.


I've faced the same problem. What I did is model Button as an entity that contains Drawable, Inputtable, and Positionable. Some properties set in Inputtable say that it's only interested in hearing about click events, and some properties set in Drawable say that it should be drawn relative to the screen, rather than the world, and some properties in Positionable give it a greater z coordinate than anything else in the scene (so that its always drawn on top.)

FWIW, I wrote a little about component based entity systems years ago, which might help to point you in the right direction.

Between Scylla and Charybdis: First Look <-- The game I'm working on

Object-Oriented Programming Sucks <-- The kind of thing I say


What is a Widget? What inextricable properties does Widget possess? If it's synonymous with Entity, like Sprite was, then the answer is probably "nothing." A Widget on its own carries no inherent properties. You're almost always going to end up having an invisible Widget, or a Widget that doesn't care about input, or that can't move, or has no position, or has a position in 2-space instead of 3-space, etc. etc. To me, this just says that trying to fit your game objects into a hierarchy is a bad idea, they're not concrete enough. That's why the component based approach has caught on so well, it fits the problem space much better than a more vanilla approach to OOP.


Widget is definitely a meaningless term in general. But in user interfaces, it universally means "UI element". So yes, there are things that are true for all widgets. That's probably why OO and UIs where invented together smile.png Widget isn't only the base class for code reuse, but for polymorphism, and understanding.

With my lack of experience in game development, I cannot say if classical OO makes as much sense there. I've read a lot about component-based systems lately, so maybe not. But my main sources of inspiration (the Doom 3 engine and Frictional Games's HPL1Engine) seem to be wired that way. (Both admittedly a bit aged, but I'm struggling to find good open source game code bases, let alone recent ones.)

The component-based approach seems like a good idea, definitely more flexible. But I'm not sure if it's the right choice in my situation. I'm working on a small-ish 2D game with pretty simple gameplay, mostly myself. You're saying: "It’s not that an inheritance based entity system is inherently wrong per se, but in large systems it tends to become an impossible to manage web of sloppy code". I'm not working on a large system, I think it makes sense to keep things as simple as possible.


I've faced the same problem. What I did is model Button as an entity that contains Drawable, Inputtable, and Positionable.


Hm. I think it makes a lot of sense to think about my game objects in terms of components, even if I don't use a component-based system. In my case this would be:

Entity

  • Can be drawn
  • Can be updated

Widget

  • Can be drawn
  • Handles its own input
  • Can contain other widgets


Looking at this, it seems I cannot reasonably derive one from the other. A widget is not updated by the game loop, it handles input itself and invokes callbacks. And it contains other widgets, to which it forwards any relevant input. Entities on the other hand are regularly updated by the scene, which handles all user input and decides what should happen to the entities based on it.

Now how does that distinction fit in with scenes? Should scenes be able to handle both entities and widgets? Should I have a special kind of entity that acts as a container for a widget? I'm stumped.
Single Responsiblity Principal

In my own personal lexicon 'Sprite' is one type of inheritor from abstract 'RenderObject', which represents anything that can be individually rendered during a frame according to its current internal state. Sprite, in particular, contains a pointer to a 'Bitmap' (responsible for a single texture and its relevant info/loading/etc), an x/y screen position, and a rect of some form indicating the source-rect from the Bitmap to draw with. An entity usually carries its own Sprite object, but Sprite itself is not an entity.

Sprite HAS-A Bitmap, which it uses as the texture to render itself with.
Sprite IS-A RenderObject because if you call .render() then it renders according to its internal state. (I actually use RenderObject to obscure registration with a list of objects in the 'Graphics' namespace that have their render() member function called by Graphics::update() if their 'visible' boolean member is true.)
In my games an Entity HAS-A Sprite so that it can be displayed on the screen when appropriate.
Each Entity is responsible for keeping the members of its member Sprite up-to-date so that when Graphics::update() is called everything gets drawn correctly.

For UI elements I may compose a class for simple elements that HAS-A Sprite, or more than one. Otherwise, if I feel it's better for the structure I may create a separate RenderObject inheritor to draw (but not implement any logic for) some complex UI element. That class HAS-A RenderObject, but it itself can't claim that it IS-A RenderObject, since it's responsible for encapsulating the UI element state/logic, not for drawing.

That's just how I do it, though. I suppose it can mean different things to different people. I've heard some people refer to a texture as a sprite, or a cell within a multi-celled texture as sprite (calling the full texture a 'sprite-sheet').
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

The component-based approach seems like a good idea, definitely more flexible. But I'm not sure if it's the right choice in my situation. I'm working on a small-ish 2D game with pretty simple gameplay, mostly myself. You're saying: "It’s not that an inheritance based entity system is inherently wrong per se, but in large systems it tends to become an impossible to manage web of sloppy code". I'm not working on a large system, I think it makes sense to keep things as simple as possible.


FWIW, the component based approach is only more difficult while you're wrapping your head around how it works. I think it's easier after that, but I feel where you're coming from anyway.


And it contains other widgets, to which it forwards any relevant input.


Is it otherwise impossible for Entities to contain other Entities? It's not uncommon to want a parent-child relationship between entities in a game. Say, there's a knife on the ground, and your character goes and picks it up. You could just "attach" the knife to the character, if you had that capability.


Now how does that distinction fit in with scenes? Should scenes be able to handle both entities and widgets? Should I have a special kind of entity that acts as a container for a widget? I'm stumped.


Both solutions are reasonable, but if you're starting out by saying that Widgets are fundamentally different than Entities--by putting them in separate trees--then you can't expect to handle them as if they are the same. You could maintain your WidgetSpace separately from your Scene. In WidgetSpace things are oriented and positioned with normalized coordinates relative to the screen, in the Scene things are positioned in absolute coordinates relative to the world. WidgetSpace can forward input for Widgets to handle on their own, while Scenes can handle input for Entities.

Between Scylla and Charybdis: First Look <-- The game I'm working on

Object-Oriented Programming Sucks <-- The kind of thing I say


Is it otherwise impossible for Entities to contain other Entities? It's not uncommon to want a parent-child relationship between entities in a game. Say, there's a knife on the ground, and your character goes and picks it up. You could just "attach" the knife to the character, if you had that capability.


Hm. I guess it does make sense. That means the major problem is really that my widgets want to handle input themselves. But that's solvable if widgets are derived from entities.


Both solutions are reasonable, but if you're starting out by saying that Widgets are fundamentally different than Entities--by putting them in separate trees--then you can't expect to handle them as if they are the same. You could maintain your WidgetSpace separately from your Scene. In WidgetSpace things are oriented and positioned with normalized coordinates relative to the screen, in the Scene things are positioned in absolute coordinates relative to the world. WidgetSpace can forward input for Widgets to handle on their own, while Scenes can handle input for Entities.


Maybe it really does make sense if I don't try to force my UI into the same object hierarchy. I've discovered a new open source code base for inspiration: Battle for Wesnoth. Like my game, they have a lot of UI. And they have that distinction.

Anyway, I'm only working on the UI for now, being the first thing we want to get right. I'll worry about entities when I actually need them, until then it's widgets. But I feel I have a couple of options available now, thank you.

This topic is closed to new replies.

Advertisement