Touch Thumbsticks Sample
This sample demonstrates a technique for using the touch panel to provide thumbstick-style controls for a game.
Sample Overview
The sample contains a simple shooter game controlled by holding the phone in landscape orientation, and by using two sides of the screen as thumbsticks. The class that implements the thumbstick logic is segregated for easy reuse in other games using the same control scheme.
Sample Controls
This sample uses the following keyboard and gamepad controls:
Action | Windows Phone |
---|---|
Accelerate | Touch left side of screen, and drag in direction to move |
Fire | Touch right side of screen, and drag in direction to move |
Exit | BACK |
How the Sample Works
The VirtualThumbsticks class handles the logic of tracking thumbstick presses. For consistency with XNA input methods, it is implemented as a static class. The game must call the VirtualThumbsticks.Update method once per game update, and at any time can access current thumbstick positions as VirtualThumbsticks.LeftThumbstick and VirtualThumbsticks.RightThumbstick.
VirtualThumbsticks keeps track of center position and current touch ID for the left and right thumbsticks. If a new touch lands on one side of the screen, and there is no active touch ID being tracked on that side, it becomes the active ID. The initial touch location is stored to define the stick center until the user touches again.
Dropped Touch Events
The XNA TouchPanel API provides only a polling interface. Your game can query to find the current touch status, but cannot sign up for notification of touch begin/end events. This presents some difficulty with this sample, because the player's point of initial contact with the screen defines the center of the thumbstick. If this point is lost because a frame or two is dropped, the center will not be where the player expects it, and the controls will not feel correct.
Fortunately, the XNA TouchPanel API provides a partial solution by providing a TryGetPreviousLocation method on TouchLocation, which allows one event's worth of history to be kept. As long as the game maintains a good frame rate, this is sufficient to keep the controls responsive.
Extending the Sample
This sample could be turned into a simple, but complete, game by adding scorekeeping, sound (some sound files are included), and hit detection on the player's ship.
The VirtualThumbsticks class is hardwired to split the screen into two sticks. A more flexible class could be configured with a set of regions to track.