Day 5: Let’s add new forms of input.
Posted by Plaidman on March 31st, 2010
Today we add a very important feature to the game. Some Android devices don’t come with a keyboard, so we must allow users of such devices to play the game using the touch screen. We’ll also add diagonal movement into the mix and make it so we can add solid walls into the map.
First step in the touchscreen process is to divide the screen into nine parts – four cardinal directions, diagonals, and center. Android comes with a really handy Rect object that stores a series of coordinates (like the Coord object from yesterday) that represent the top left and bottom right corners of a rectangle, and a Rect.contains(x,y) method that tells you if an X,Y point is contained in the rectangle. This is very easy stuff to do myself, but why reinvent the wheel, right? Right. We’ll make nine of these to store the nine regions of the screen, and We’ll test the X,Y touch point against each to figure out which direction Red should go.
Next we need to capture when the user taps on the screen. Android makes this easy for us by allowing us to override certain system calls; we can say “instead of doing what you normally do for screen taps, do this“. This, in this case, will be to move Red one square in the direction we tapped.
I should mention that TouchEventListener (aptly named, as it listens for when the user touches the screen then does what we want) listens for three events: TOUCH, MOVE, and RELEASE. Interestingly, the system ignores all RELEASE events unless we acknowledge a TOUCH event. This make sense because a RELEASE event should not be expected without a TOUCH event, but it’s annoying because we might not care to do anything when the user touches the screen, only releases, and we don’t want to have to take the extra step to acknowledge it. This doesn’t affect my game because I’m doing everything on TOUCH, for now.
Now we have our touch screen mapped to eight directions and a center (unused for now), and we have our previous movement code from the keyboard. We just copy it over and be done right? WRONG! Repeating code is generally bad – it’s sloppy and difficult to maintain. Let’s say we need to update our movement algorithm, so we update it in the touch screen but forget to update it in the keyboard. The game might act weird at best and catastrophically fail at worst. Instead, we’ll move the character movement code into the Character class, and call the Character’s movement functions from both the touch screen Listener and the keyboard Listener.
Current demo: Red can move diagonally using either the keypad or the touch screen. He is now trapped in a predefined map with corridors and rooms and walls.