Wednesday, February 24, 2016

c++ - Should an object in a 2D game render itself?


I'm making a 2D street fighter-like game that is not tile based. Usually people recommend that entities be given to a renderer that render them, not them render themselves, but it seems the inverse is better,


Why is one better over the other?


Thanks



Answer




An couple of considerations :




  • as you mentionned, each sprite would have to "hint" about which bitmap to use, but if the entity has to render itself. What would that 'hint' be ? If it is a reference to a different bitmap, sprite sheet, etc... for each sprite, then you might end up using more memory than necessary, or having troubles managing that memory. An advantage of a separate renderer is that you have only one class responsible for any asset management. That said, in a SF2-like fighting game, you might only have two sprites ;)




  • as mentionned elsewhere, whenever you want to change your graphical API, you have to change the code for all your sprites.




  • rendering is rarely done whithout a reference to some graphical context. So either there is a global variable that represent this concept, or each sprite has an interface with render(GraphicalContext ctx). This mixes the graphical API and the logic of your game (which some people will find unelegant), and might cause compilation issues.





  • I personnaly find that separating the rendering from the individual entities is an interesting first step in the direction of viewing your game as a system that does not necessarily need graphics at all. What I mean is that when you put rendering out of the way, you realize lots of the gameplay happens in a "non-graphic world" where the coordinates of the entities, their internal states, etc... is what matters. This opens the door to automated testing, more decoupled system, etc...




All in all, I tend to prefer systems where rendering is done by a seperate class. That does not mean your sprites can not have some attributes that are "graphically related" (animation name, animation frame, height x width, sprite id etc... ), if that makes the renderer easier to write or more efficient.


And I don't know if that would apply to 3D (where the notion of meshes, and the coordinates variable you would use would maybe be tied to your 3D API ; whereas x,y,h,w is pretty much independant of any 2D API).


Hoping this helps.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...