2013-03-16 92 views
0

我正在用Cocos2d为iPhone构建游戏,现在我正试图让Touch输入工作。我已经在多层场景中的独立控制层上启用了触摸响应,并且它工作正常 - 除非触摸方法在触摸位于单独图层上的精灵顶部时触发触摸方法(单独的图层为实际上只是一个节点)。除了这个精灵之外,我没有其他的屏幕内容。Cocos2d输入图层仅接收精灵顶部的触摸

这里是我的控制层实现:

#import "ControlLayer2.h" 

extern int CONTROL_LAYER_TAG; 
@implementation ControlLayer2 
+(void)ControlLayer2WithParentNode:(CCNode *)parentNode{ 
    ControlLayer2 *control = [[self alloc] init]; 
    [parentNode addChild:control z:0 tag:CONTROL_LAYER_TAG]; 
} 

-(id)init{ 
    if (self=[super init]){ 

     [[[CCDirector sharedDirector]touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES]; 
    } 
    return self; 
} 

-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{ 
    CCLOG(@"touchbegan"); 
    return YES; 
} 

@end 

,这里是与内部具有精灵的子节点层:

extern int PLAYER_LAYER_TAG; 

int PLAYER_TAG = 1; 

@implementation PlayerLayer 
//reduces initializing and adding to the gamescene to one line for ease of use 
+(void)PlayerLayerWithParentNode:(CCNode *)parentNode{ 
    PlayerLayer *layer = [[PlayerLayer alloc] init]; 
    [parentNode addChild:layer z:1 tag:PLAYER_LAYER_TAG]; 
} 

-(id)init{ 
    if(self = [super init]){ 
     //add the player to the layer, know what I'm sayer(ing)? 
     [Player playerWithParentNode:self]; 
    } 
    return self; 
} 

@end 

最后,包含他们两个场景:

int PLAYER_LAYER_TAG = 1; 
int CONTROL_LAYER_TAG = 2; 
@implementation GameScene 

+(id)scene{ 
    CCScene *scene = [CCScene node]; 
    CCLayer *layer = [GameScene node]; 
    [scene addChild:layer z:0 tag:0]; 
    return scene; 
} 

-(id)init{ 
    if(self = [super init]){ 
     //[[[CCDirector sharedDirector]touchDispatcher] addTargetedDelegate:[self getChildByTag:0] priority:0 swallowsTouches:YES]; 
     //add the player layer to the game scene (this contains the player sprite) 
     [ControlLayer2 ControlLayer2WithParentNode:self]; 
     [PlayerLayer PlayerLayerWithParentNode:self]; 

    } 
    return self; 
} 

@end 

我该如何使控制层响应所有触摸输入?

回答

1

在init方法中添加此代码。

self.touchEnabled = YES; 

,并使用此ccTouchesBegan

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

    //handle touch 
} 

在你的代码删除此行:

[[[CCDirector sharedDirector]touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES]; 

UPDATE:HERE IS FULL CODE

+0

我想这一点,达到同样的效果。 – Swanijam 2013-03-16 16:59:06

+0

ControlLayer2的父级是GameScene。在GameScene中未启用触摸。因此,在GameScene中放置self.touchEnabled = YES并将ccTouchesBegan放在相同的位置... – Guru 2013-03-16 17:00:39

+0

将所有触摸控件放入GameScene中?我想我可以,但是我想在一个单独的课程中处理所有的问题,以确保代码和组织的清晰。或者你的意思是把self.touchEnabled放在gamescene中,但是ControlLayer2类中的触摸控件? – Swanijam 2013-03-16 17:06:11