0

*Working Code Now*

OK, I thought that this would be easy to get working but it turns out to not work like I expected.

I am trying to get the Touch location from a CCLayer that can be moved or zoomed, not the location on the screen itself? here is how I thought that it would work but it crashes?

Interface #import "cocos2d.h"

@interface TestTouch : CCLayer {
   CCLayerColor *layer;
}

+(CCScene *) scene;


@end

Implementation

#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

If I change this line to include "self":

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

It will obviously work but then I get the location relevant to the screen and not the layer, which is what I need.

EcksMedia
  • 461
  • 2
  • 5
  • 20

1 Answers1

1

You need to convert the location on the screen to the layer's "node space":

- (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;
}
CodeSmile
  • 64,284
  • 20
  • 132
  • 217
  • Unfortunately that makes no difference but thank you very much for the answer. I tried to set the touchDispacher to both layer and self but it still crashes on layer. I have set up a test project for this and modified the original question with the exact running, faulty code. – EcksMedia Oct 16 '11 at 10:44
  • You are a Legend. I spent a few mins playing around and found that you were actually spot on with your answer but I need to set up layer as an Var and change [self convertToNodeSpace:touchStart]; to [layer convertToNodeSpace:touchStart]; – EcksMedia Oct 16 '11 at 10:56