Tuesday, March 31, 2015

rendering - Should actors in a game be responsible for drawing themselves?


I am very new to game development, but not to programming.


I am (again) playing around with a Pong type game using JavaScript's canvas element.


I have created a Paddle object which has the following properties...



  • width


  • height

  • x

  • y

  • colour


I also have a Pong object which has properties such as...



  • width

  • height

  • backgroundColour


  • draw().


The draw() method currently is resetting the canvas and that is where a question came up.


Should the Paddle object have a draw() method responsible for its drawing, or should the draw() of the Pong object be responsible for drawing its actors (I assume that is the correct term, please correct me if I'm incorrect).


I figured that it would be advantagous for the Paddle to draw itself, as I instantiate two objects, Player and Enemy. If it were not in the Pong's draw(), I'd need to write similar code twice.


What is the best practice here?


Thanks.



Answer



Having actors draw themselves is not a good design, for two main reasons:


1) it violates the single responsibility principle, as those actors presumably had another job to do before you shoved render code into them.



2) it makes extension difficult; if every actor type implements its own drawing, and you need to change the way you draw in general, you may have to modify a lot of code. Avoiding overuse of inheritance can alleviate this to some extent, but not completely.


It's better for your renderer to be handling the drawing. After all, that's what it means to be a renderer. The renderer's draw method should take a "render description" object, which contains everything you need to render a thing. References to (probably shared) geometry data, instance-specific transformations or material properties such as color, et cetera. It then draws that, and doesn't care what that render description is supposed to "be."


Your actors can then hold on to a render description they create themselves. Since actors are typically logic processing types, they can push state changes to the render description as needed -- for example, when an actor takes damage it could set the color of its render description to red to indicate this.


Then you can simply iterate every visible actor, enqeue their render descriptions into the renderer, and let it do its thing (basically; you could generalize this even further).


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...