Cocos2d中的触摸精灵
问题描述:
我试图创建一个可以检测触摸的扩展CCSprite类。我做了一些研究,并在http://anny.fm/c/iphone/cocos2d/TouchableSprite/上发现了一个由Anny在本论坛主题http://www.cocos2d-iphone.org/forum/topic/3196(最新文章)中创建的示例。Cocos2d中的触摸精灵
使用这个我已经安装我的课像这样:
页眉
#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所以我想它可能是做与...
答
你并不需要有针对性的触摸代表,它只是分裂触摸到个人ccTouchXXX消息的NSSet。您的实现仅仅缺乏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];
只是说你不会有做这一切工作。 ;)
谢谢,你在哪里现货!嗯,一行..我必须检查Kobold2D了。 – Alex