Skip to content

Instantly share code, notes, and snippets.

@jonsterling
Created May 31, 2010 04:18
Show Gist options
  • Select an option

  • Save jonsterling/419523 to your computer and use it in GitHub Desktop.

Select an option

Save jonsterling/419523 to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h>
#import "cocos2d.h"
@protocol JSSpriteTouching
@optional
- (void)actOnTouch;
- (void)actOnTouchWithPosition:(CGPoint)pos;
@end
@interface JSTouchSprite : Sprite {
BOOL tracked;
}
+ (NSMutableArray *)allSprites;
+ (void)track:(JSTouchSprite *)sprite;
+ (void)untrack:(JSTouchSprite *)sprite;
+ (BOOL)spriteWasTouchedAtPosition:(CGPoint)pos;
+ (JSTouchSprite *)spriteTouchedAtPosition:(CGPoint)pos;
+ (JSTouchSprite *)spriteWithTag:(int)tag;
- (CGRect)rect;
@end
#import "JSTouchSprite.h"
@interface JSTouchSprite ()
@property (nonatomic, getter=isTracked) BOOL tracked;
@end
@implementation JSTouchSprite
@synthesize tracked;
static NSMutableArray *allSprites = nil;
+ (NSMutableArray *)allSprites {
@synchronized(allSprites) {
if (allSprites == nil)
allSprites = [[NSMutableArray alloc] init];
return allSprites;
} return nil;
}
+ (void)track:(JSTouchSprite *)sprite {
@synchronized(allSprites) {
for (JSTouchSprite *obj in allSprites) {
if (obj == sprite)
return;
}
[[JSTouchSprite allSprites] addObject:sprite];
}
}
+ (void)untrack:(JSTouchSprite *)sprite {
@synchronized(allSprites) {
[[JSTouchSprite allSprites] removeObject:sprite];
}
}
+ (BOOL)spriteWasTouchedAtPosition:(CGPoint)pos {
for (JSTouchSprite *obj in allSprites) {
if (CGRectContainsPoint([obj rect], pos)
&& [obj isTracked])
return YES;
} return NO;
}
+ (JSTouchSprite *)spriteTouchedAtPosition:(CGPoint)pos {
for (JSTouchSprite *obj in allSprites) {
if (CGRectContainsPoint([obj rect], pos) && [obj isTracked])
return obj;
} return nil;
}
+ (JSTouchSprite *)spriteWithTag:(int)tag {
for (JSTouchSprite *obj in allSprites) {
if ([obj tag] == tag)
return obj;
} return nil;
}
- (id)init {
self = [super init];
if (self != nil) {
[JSTouchSprite track:self];
[self setTracked:YES];
} return self;
}
- (CGRect)rect {
float w = [self contentSize].width;
float h = [self contentSize].height;
CGPoint point = CGPointMake([self position].x - (w/2), [self position].y - (h/2));
return CGRectMake(point.x, point.y, w, h);
}
- (void)dealloc {
[JSTouchSprite untrack:self];
[super dealloc];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment