Cocos2d中可触摸的精灵

时间:2011-11-15 23:18:58

标签: cocos2d-iphone touch

我正在尝试创建一个可以检测触摸的扩展CCSprite类。我做了一些研究,并在http://anny.fm/c/iphone/cocos2d/TouchableSprite/发现了一个由Anny在这个论坛帖子http://www.cocos2d-iphone.org/forum/topic/3196(最后一篇文章)中创建的例子。

使用这个我设置我的课程如下:

标题

#import <Foundation/Foundation.h>
#import "cocos2d.h"

@interface PianoKey : CCSprite <CCTargetedTouchDelegate> {

}

-(BOOL) tsTouchBegan:     (UITouch*)touch withEvent: (UIEvent*)event;
-(void) tsTouchMoved:     (UITouch*)touch withEvent: (UIEvent*)event;
-(void) tsTouchEnded:     (UITouch*)touch withEvent: (UIEvent*)event;
-(void) tsTouchCancelled: (UITouch*)touch withEvent: (UIEvent*)event;

@end

和实施......

@implementation PianoKey

-(id)initWithKey:(int)key {
if((self = [super initWithFile:[NSString stringWithFormat:@"key_%i.png",key]])) {

}
return self;
}


 -(BOOL) tsTouchBegan:(UITouch*)touch withEvent: (UIEvent*)event { 
NSLog( @"tsTouchBegan"); 
return YES; 
}
 -(void) tsTouchMoved:(UITouch*)touch withEvent: (UIEvent*)event { 
NSLog( @"tsTouchMoved"); 

} 
-(void) tsTouchEnded:(UITouch*)touch withEvent: (UIEvent*)event { 
NSLog( @"tsTouchEnded");

}
-(void) tsTouchCancelled:(UITouch*)touch withEvent: (UIEvent*)event { 
NSLog( @"tsTouchCancelled");
}

//
// Utilities. Don't override these unless you really need to.
//

-(CGRect) rect {
CGSize s = [self.texture contentSize];
return CGRectMake(-s.width / 2, -s.height / 2, s.width, s.height);
}

-(BOOL) didTouch: (UITouch*)touch {
return CGRectContainsPoint( [self rect], [self convertTouchToNodeSpaceAR: touch] );
}

//
// The actual touch listener functions. Don't override these either.
//

-(BOOL) ccTouchBegan:(UITouch*)touch withEvent: (UIEvent*)event { 
    NSLog(@"attempting touch.");
    if([self didTouch: touch]) {
        return [self tsTouchBegan:touch withEvent: event]; 
    }
return NO; 
}
-(void) ccTouchMoved:     (UITouch*)touch withEvent: (UIEvent*)event { if([self didTouch: touch])        [self tsTouchMoved:     touch withEvent: event]; }
-(void) ccTouchEnded:     (UITouch*)touch withEvent: (UIEvent*)event { if([self didTouch: touch])        [self tsTouchEnded:     touch withEvent: event]; }
-(void) ccTouchCancelled: (UITouch*)touch withEvent: (UIEvent*)event { if([self didTouch: touch])        [self tsTouchCancelled: touch withEvent: event]; }

@end

我理解上面的方法,例如检测触摸是否在精灵的范围内,但是当我点击键时,我不知道为什么我没有得到任何响应。我刚开始实现CCTargetdTouchDelegate所以我认为它可能与此有关......

1 个答案:

答案 0 :(得分:0)

您不需要有针对性的触摸委托,它只是将NSSet触摸分成单独的ccTouchXXX消息。您的实施只是缺少CCTargetedTouchHandler的注册和注销。这通常在onEnter中完成,因此它适用于任何节点类型而不仅仅是CCLayer:

-(void) onEnter
{
    [super onEnter];
    [[TouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:INT_MIN+1 swallowsTouches:YES];
}

-(void) dealloc
{
    [[TouchDispatcher sharedDispatcher] removeDelegate:self];
    [super dealloc];
}

顺便说一下,Kobold2D已经有了一个扩展的CCNode类,可以通过这个测试测试节点上是否有触摸(精灵,标签等):

[node containsTouch:uiTouch];

只是说你不必做所有这些工作。 ;)