Extending cocos2d CCSprite to Handle Touches

I Wanna Touch U, Till We're Stuck Like Glue

Mar 04, 2012 | image credit

Extending CCSprite Makes My Life Easier

While developing a couple of games that I am currently working on I ended up finding a need to have a CCSprite that would trigger a particular selector. I wanted something lightweight that I could just throw into anything. So I went about writing a quick subclass of CCSprite that at first I thought would be a bit of a throw away one time use thing. It turned out however to be simple and reusable and I find myself reusing the class all over the place, enter ClickableSprite.

The concept is dead simple create a subclass of CCSprite adhering to CCTargetedTouchDelegate, and give it a couple of properties that will store a target and selector. Here’s the class definition, don’t forget to synthesize those properties though!

1 @interface ClickableSprite : CCSprite <CCTargetedTouchDelegate> 
3 @property (nonatomic, assign) id<NSObject> target;
4 @property (nonatomic) SEL selector;
6 @end

Handling The Touches

In the implementation file we’ll implement a function (containsTouchLocation:) that will test whether or not a touch is contained by the sprite. This method was lifted from some place or another, I don’t really remember.

1 - (BOOL)containsTouchLocation:(UITouch *)touch {
2     CGPoint p = [self convertTouchToNodeSpaceAR:touch];
3     CGSize size = self.contentSize;
4     CGRect r = CGRectMake(-size.width*0.5, 
5                           -size.height*0.5, 
6                           size.width, 
7                           size.height);
8     return CGRectContainsPoint(r, p);
9 }

Next we want to implement ccTouchBegan:withEvent and ccTouchEnded:withEvent such that when a user touches the sprite and then lifts their finger without moving it off of the sprite it will fire it’s selector.

1 - (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
2     return [self containsTouchLocation:touch];
3 }
5 - (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
6     if(![self containsTouchLocation:touch])
7         return;
8     [ performSelector:self.selector withObject:self];
9 }

Finally we will want to add the sprite as a targeted delegate to the CCTouchDispatcher singleton, we’ll just do this in the onEnter. And of course we’ll want to remove the sprite from the delegate list when it goes away (otherwise we’ll get EXC\BAD\ACCESS when the CCTouchDispatcher tries to get at it).

1 - (void)onEnter {
2     [super onEnter];
3     [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
4 }
6 - (void)onExit {
7     [[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
8     [super onExit];
9 }

Make That Target Bigger So Your Grandma Can Hit it

That’s great, it works pretty well, but sometimes you want to be able to press a sprite that is kind of small, let’s just add another property clickableSize and synthesize it.

1 @property (nonatomic) CGSize clickableSize;

Then we can modify our containsTouchLocation function to check for this like so…

1 - (BOOL)containsTouchLocation:(UITouch *)touch {
2     CGPoint p = [self convertTouchToNodeSpaceAR:touch];
3     CGSize size = self.contentSize;
4     if(!CGSizeEqualToSize(self.clickableSize, CGSizeZero))
5         size = self.clickableSize;
6     CGRect r = CGRectMake(-size.width*0.5, -size.height*0.5, size.width, size.height);
7     return CGRectContainsPoint(r, p);
8 }

One More Thing

Oh, and one more thing you might like is to be able to set the priority. CCTouchDispatcher will go through all of its delegates in order of priority, lower being called first. I haven’t found that I need to set the priority after it has been added to the scene so I haven’t bothered to implement that functionality. At any rate we’ll add another property touchPriority

@property (nonatomic) int touchPriority;

And then simply modify our onEnter function

1 - (void)onEnter {
2     [super onEnter];
3     [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:self.priority swallowsTouches:YES];
4 }

To use the sprite you initialize it as you would a normal CCSprite, set the relevant properties, and add to a node like any other sprite as well.

1 ClickableSprite *sprite = [ClickableSprite spriteWithFile:@"myAwesomeSprite.png"];
2 = self;
3 sprite.selector = @selector(myAwesomeSelector); 
4 // Or with the sprite as an argument sprite.selector = @selector(myAwesomeSelector:); 
5 // which would call a function that would look like 
6 // - (void)myAwesomeSelector:(ClickableSprite *)clickableSprite
7 sprite.clickableSize = CGSizeMake(100,100);
8 sprite.touchPriority = 2;

Now we have a nice simple class that we can reuse over and over again.