触摸位置CCLayer

时间:2011-10-16 04:27:38

标签: ios cocos2d-iphone cclayer

* 立即使用代码 *

好吧,我认为这很容易上班,但结果却不像我预期的那样。

我试图从可以移动或缩放的CCLayer获取Touch位置,而不是屏幕本身的位置?这是我认为它会起作用但崩溃的方式?

接口     #import“cocos2d.h”

@interface TestTouch : CCLayer {
   CCLayerColor *layer;
}

+(CCScene *) scene;


@end

实施

#import "TestTouch.h"

@implementation TestTouch

+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];

// 'layer' is an autorelease object.
TestTouch *layer = [TestTouch node];

// add layer as a child to scene
[scene addChild: layer];

// return the scene
return scene;
}

- (id)init
{
    self = [super init];
    if (self) {
        CGSize winsize = [[CCDirector sharedDirector]winSize];
        CCLayerColor *layer = [CCLayerColor layerWithColor:ccc4(255, 255, 255, 255)];
//        layer.scale = 0.7f;
        layer.contentSize = CGSizeMake(640, 960);
        layer.position = CGPointMake(winsize.width/2, winsize.height/2);
        layer.isRelativeAnchorPoint = YES;
        [self addChild:layer z:0];
        [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:layer priority:0 swallowsTouches:YES];
    }

    return self;
}

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    CGPoint touchStart = [[CCDirector sharedDirector] convertToGL:[touch locationInView:[touch view]]];
    touchStart = [layer convertToNodeSpace:touchStart];
    NSLog(@"Touch:%f,%f",touchStart.x, touchStart.y);

    return YES;
}

@end

如果我将此行更改为包含“self”:

  

[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];

它显然会起作用,但后来我得到的位置与屏幕相关,而不是图层,这就是我需要的。

1 个答案:

答案 0 :(得分:1)

您需要将屏幕上的位置转换为图层的“节点空间”:

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    CGPoint touchStart = [[CCDirector sharedDirector] convertToGL:[touch locationInView:[touch view]]];

    // convert touch location to layer space
    touchStart = [self convertToNodeSpace:touchStart];

    NSLog(@"Touch:%f,%f",touchStart.x, touchStart.y);

    return YES;
}