Game Development Reference
In-Depth Information
36 @bullets . map( & :draw )
37 end
38 end
39 @camera . draw_crosshair
40 end
41
42 def button_down ( id )
43 if id == Gosu :: MsLeft
44 bullet = @tank . shoot( * @camera . mouse_coords)
45 @bullets << bullet if bullet
46 end
47 $window . close if id == Gosu :: KbQ
48 if id == Gosu :: KbEscape
49 GameState . switch( MenuState . instance)
50 end
51 end
52
53 end
Update and draw calls are passed to the underlying game entities, so they can handle them
the way they want it to. Such encapsulation reduces complexity of the code and allows
doing every piece of logic where it belongs, while keeping it short and simple.
There are a few interesting parts in this code. Both @tank.update and @tank.shoot
may produce a new bullet, if your tank's fire rate is not exceeded, and if left mouse
button is kept down, hence the update . If bullet is produced, it is added to @bullets
array, and they live their own little lifecycle, until they explode and are no longer used.
@bullets.reject!(&:done?) cleans up the garbage.
PlayState#draw deserves extra explanation. @camera.x and @camera.y points to
game coordinates where Camera is currently looking at. Gosu::Window#translate
creates a block within which all Gosu::Image draw operations are translated by given
offset. Gosu::Window#scale does the same with Camera zoom.
Crosshair is drawn without translating and scaling it, because it's relative to screen, not to
world map.
Basically, this draw method is the place that takes care drawing only what @camera can
see.
Search WWH ::




Custom Search