*现在工作代码*
好的,我认为这很容易开始工作,但结果却不像我预期的那样工作。
我正在尝试从可以移动或缩放的 CCLayer 获取触摸位置,而不是屏幕本身的位置?这就是我认为它会工作但它崩溃的方式?
接口 #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:0swallowsTouches:YES];
它显然会起作用,但随后我得到了与屏幕相关的位置,而不是与图层相关的位置,这正是我所需要的。