在自己的layer里面,添加
[self setIsTouchEnabled:YES];
以下方法是cocos2d类库的方法:
-(void) setIsTouchEnabled:(BOOL)enabled
{
if( isTouchEnabled_ != enabled ) {
isTouchEnabled_ = enabled;
if( isRunning_ ) {
if( enabled )
[self registerWithTouchDispatcher];
else {
CCDirector *director = [CCDirector sharedDirector];
[[director touchDispatcher] removeDelegate:self];
}
}
}
}
//这句是关键
-(void) registerWithTouchDispatcher
{
CCDirector *director = [CCDirector sharedDirector];
[[director touchDispatcher] addStandardDelegate:self priority:0];
}
接下来就实现方法:
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
// for( UITouch *touch in touches ) {
// CGPoint location = [touch locationInView: [touch view]];
//
// location = [[CCDirector sharedDirector] convertToGL: location];
// CGPoint touchPos = location;
//
// NSLog(@"point==%@",NSStringFromCGPoint(touchPos));
// }
UITouch* touch = [touches anyObject];
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL: location];
//self.position = location;
NSLog(@"point==%@",NSStringFromCGPoint(location));
}
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
self.isMoving = FALSE;
}
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
// you can set up a check here if you're not interested in handling every touch.
// For example if your player is already moving, return no...
BOOL handleTouch = FALSE;
if (!self.isMoving) {
handleTouch = TRUE;
self.isMoving = TRUE;
}
return handleTouch;
}