我有这个精灵,我试图检测用户是否触摸并发布NSLOG。我已经阅读了一些关于在stackoverflow上检测精灵触摸的cocos2d帖子,但我有点困惑并且不太明白。任何帮助将不胜感激。我将在下面发布我的精灵。
chew = [CCSprite spriteWithFile:@"chew.png" rect:CGRectMake(0, 0, 152, 152)];
chew.position = ccp(100, 300);
[self addChild:chew];
想出来
-(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");
}
}
答案 0 :(得分:5)
为您的精神提供标记值,并在触摸事件中比较该标记值
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;
}
答案 1 :(得分:2)
试试这个
- (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;
}
}
当然,在你的init中,你必须设置self.isTouchEnabled = YES;
答案 2 :(得分:0)
-(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 ...
}
}