* Now* 工作代码
好的,我以为这会很容易得到工作,但结果不是我所期望的那样工作。
我试图从一个可以移动或缩放的CCLayer中获取触摸位置,而不是屏幕上的位置?我是这么想的,但它会崩溃吗?
接口#导入"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优先级:0燕尾触觉:是];
它显然会工作,但然后我得到与屏幕相关的位置,而不是图层,这是我所需要的。
发布于 2011-10-16 10:11:04
您需要将屏幕上的位置转换为该层的“节点空间”:
- (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;
}https://stackoverflow.com/questions/7782341
复制相似问题