0

在这个 cocos2d 应用程序中,当我按下 ccsprite 时,nslog 没有触发。有人可以帮助我吗?

-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{
NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init];
for (CCSprite *target in _targets) {
    CGRect targetRect = CGRectMake(target.position.x - (target.contentSize.width/2), 
                                   target.position.y - (target.contentSize.height/2), 
                                   27, 
                                   40);


CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
if (CGRectContainsPoint(targetRect, touchLocation)) {            
    NSLog(@"Moo cheese!");
    }
}
return YES;   
}
4

2 回答 2

3

首先确保将触摸精灵注册到onEnter方法中,例如:

- (void)onEnter
{
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:defaultTouchPriority_ swallowsTouches:YES];
    [super onEnter];
}

这将使您的精灵可触摸,并在用户按下它时将事件触发给精灵。然后重构您的代码以使其更具可读性并测试类似的内容:

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    CGPoint touchLocation = [self convertTouchToNodeSpace:touch];

    NSArray *targetsToDelete = [self touchedSpritesAtLocation:touchLocation];

    // Put your code here
    // ...

    return YES;
}

- (NSArray *)touchedSpritesAtLocation:(CGPoint)location
 {
    NSMutableArray *touchedSprites = [[NSMutableArray alloc] init];

    for (CCSprite *target in _targets)
        if (CGRectContainsPoint(target.boundingBox, location))
            [touchedSprites addObject:target];

    return [touchedSprites autorelease];
}

它应该返回已触及的目标。

于 2012-07-07T21:01:20.320 回答
0

在层初始化方法中添加这个

self.isTouchEnabled = true;

使用此代码进行触摸检测

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *myTouch = [touches anyObject];
    CGPoint location = [myTouch locationInView:[myTouch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];

    CGRect rect = [self getSpriteRect:yourSprite];

    if (CGRectContainsPoint(rect, location))
    {
        NSLog(@"Sprite touched\n");
    }

}

要获得精灵矩形:

-(CGRect)getSpriteRect:(CCNode *)inSprite
{
    CGRect sprRect = CGRectMake(
                                inSprite.position.x - inSprite.contentSize.width*inSprite.anchorPoint.x,
                                inSprite.position.y - inSprite.contentSize.height*inSprite.anchorPoint.y,
                                inSprite.contentSize.width, 
                                inSprite.contentSize.height
                                ); 

    return sprRect;
}
于 2012-07-09T17:24:26.320 回答