Reputation: 37
I have this sprite that I am trying to detect if user touched it and post an NSLOG. I have read some cocos2d posts on detecting sprite touch on stackoverflow, but I got a bit confused and don't quite understand. Any help will be appreciated.I will post my sprite below.
chew = [CCSprite spriteWithFile:@"chew.png" rect:CGRectMake(0, 0, 152, 152)];
chew.position = ccp(100, 300);
[self addChild:chew];
Figured it out
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSSet *allTouches = [event allTouches];
UITouch* touch = [touches anyObject];
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
if (CGRectContainsPoint( [ chew boundingBox], location))
{
NSLog(@"touched");
}
}
Upvotes: 2
Views: 9848
Reputation: 3510
try this
- (BOOL)containsTouchLocation:(UITouch *)touch
{
if (![self visible]) return NO;
Boolean isTouch = CGRectContainsPoint(self.rect, [self convertTouchToNodeSpaceAR:touch]);
return isTouch;
}
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
if ([self containsTouchLocation:touch] )
{
NSLog(@"Touch find");
return YES;
}
else
{
return NO;
}
}
Of course, in your init, you must set self.isTouchEnabled = YES;
Upvotes: 2
Reputation: 2741
Give tag values to your spirit and in touch event compare that tag value
chew = [CCSprite spriteWithFile:@"chew.png" rect:CGRectMake(0, 0, 152, 152)];
chew.position = ccp(100, 300);
chew.tag=12;
[self addChild:chew];
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint location = [self convertTouchToNodeSpace: touch];
for (CCSprite *station in _objectList)
{
if (CGRectContainsPoint(station.boundingBox, location))
{
if(station.tag==12)
{
DLog(@"Found Your sprite");
return YES;
}
}
}
return NO;
}
Upvotes: 4
Reputation: 2251
-(void) ccTouchesBegan:(NSSet*)touches withEvent:(id)event
{
CCDirector* director = [CCDirector sharedDirector];
UITouch* touch = [touches anyObject];
CGPoint touchLocation = [touch locationInView:director.openGLView];
CGPoint locationGL = [director convertToGL:touchLocation];
CGPoint locationInNodeSpace = [chew convertToNodeSpace:locationGL];
CGRect bbox = CGRectMake(0, 0,
chew.contentSize.width,
chew.contentSize.height);
if (CGRectContainsPoint(bbox, locationInNodeSpace))
{
// code for when user touched chew sprite goes here ...
}
}
Upvotes: 0