Java Reference
In-Depth Information
Managing Events and Drawing
The GameCanvas class provides a basis for your game's visual display, including all of
the capabilities of the Canvas class (see Chapter 5, especially the section “Working
with the Canvas and Custom Items”). The class provides interfaces for managing the
following events:
Event handling : You can continue to receive key and pointer events to control your
application. As you'll soon see, you can also poll for key events, which is handy if
you're within your game's control loop.
Command handling : GameCanvas ultimately inherits from Displayable , so you
inherit all the methods pertaining to the Command infrastructure, including
addCommand , removeCommand , and setCommandListener . In practice, you won't use this
often, as raw keystrokes become the usual means for controlling a game.
Drawing : Your GameCanvas can implement paint , which is responsible for painting
the display. However, as you'll soon see, it may be more advantageous to do your
painting within your game's control loop instead.
The GameCanvas has several additional features. First, GameCanvas has its own screen
buffer associated with it. GameCanvas subclasses are assured that the only thing that can
draw to a GameCanvas buffer is the Graphics objects obtained directly from that canvas,
without interference from other controls, MIDlets, or the system. With this buffer comes
added responsibility; as graphics buffers can be large, you should be conservative when
you allocate GameCanvas objects, and reuse them whenever possible.
Second, when you create a GameCanvas subclass, you have the option of indicating
whether you want the system to dispatch key events to the canvas, or whether you
want to poll the system for key states. This is a key way to optimize your application; if
your application has a central control loop, it is usually faster to poll for key state
changes during your event loop instead of responding to key events and updating the
game state, because it saves you the overhead of a method dispatch and the complexity
of tracking control state in your event handler and responding to changes in state in
your control loop.
Finally, because your application owns its display buffer, it can draw to the buffer at
any time. Now, this isn't a call to generating graphics operations willy-nilly; such a style
can hurt game performance. However, it does invite a style of programming more famil-
iar to game programmers of yore, in which a central control loop running on its own
thread is responsible for updating game state and redrawing the display.
 
Search WWH ::




Custom Search