Game Development Reference
In-Depth Information
Applying Touch Events to Actors
Let's take a quick look at the class
TouchEventsController
and see how we set up the demo to
respond to tap gestures. The important part of
TouchEventsController.m
is shown in Listing 8-4.
Listing 8-4. TouchEventsController.m (doSetup)
-(BOOL)doSetup{
if ([super doSetup]){
[self setGameAreaSize:CGSizeMake(320, 480)];
[self setSortedActorClasses:[NSMutableArray arrayWithObject:[Spark class]]];
UITapGestureRecognizer* doubleTapTwoTouch=[[UITapGestureRecognizer alloc]
[doubleTapTwoTouch setNumberOfTapsRequired:2];
[doubleTapTwoTouch setNumberOfTouchesRequired:2];
UITapGestureRecognizer* doubleTapOneTouch=[[UITapGestureRecognizer alloc]
[doubleTapOneTouch setNumberOfTapsRequired:2];
[doubleTapOneTouch setNumberOfTouchesRequired:1];
[actorsView addGestureRecognizer:doubleTapOneTouch];
[actorsView addGestureRecognizer:doubleTapTwoTouch];
return YES;
}
return NO;
}
In Listing 8-4, we see the task
doSetup
, from the class
TouchEventsController
. This task
is called when this
UIViewController
instance's view is loaded. After setting up the game
area size and marking the class Spark as a sorted actor class, we create two instances
of
UITapGestureRecognizer
. The first instance of
UITapGestureRecognizer
is called
doubleTapTwoTouch
and is configured to respond when two fingers do a double tap. The second
UITapGestureRecognizer
is called
doubleTapOneTouch
and is configured for a single-finger
double tap. Both of these
UITapGestureRecognizer
are added to
actorsView
with the task
addGestureRecognizer
:.
Looking at the constructor used to create these gesture recognizers, we see a selector referencing
the task
doubleTap
:. This task is called whenever one of these two tasks recognizes a gesture. We
could have had each gesture recognizer call different tasks, and that may be desirable in a more
complex application. In this example, it is easy enough to distinguish these two gesture recognizers
in the
doubleTap
: tasks, as shown in Listing 8-5.