2011-03-21 61 views
0

我希望能够通过用户触摸来移动某些精灵图像。 东西沿着这些线路:如何让CCSprite跟随用户触摸ccTouchMoved

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    for (UITouch *touch in touches) 
    { 
     CGPoint *location = [touch locationInView:[touch view]]; 
     location = [[CCDirector sharedDirector] convertToGL: location]; 
     if (CGRectContainsPoint(sprite.boundingBox, location) 
     { 
      sprite.location = ccp(location.x, location.y); 
     } 
    } 
} 

当然,对我来说这并不工作,因为有此方法连续移动CCSprite运行没有打勾方法。我知道的方法ccTouchMoved,但我不确定如何实现它,任何示例将不胜感激。

回答

4

只有CClayer能够检测到触摸,其自动。所以你将需要处理每个刻度的事情。它应该是ccTouchesMove ..喜欢的东西:

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    NSLog(@"begin"); 
} 

-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{  
    UITouch *touch = [touches anyObject]; 
    CGPoint location = [touch locationInView: [touch view]]; 
    location = [[CCDirector sharedDirector] convertToGL:location]; 

    sprite.position = location; 
} 

-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    NSLog(@"Ended"); 
} 

当然,在你的初始化,您必须设置self.isTouchEnabled = YES;

2

您可以将子画面图像与场景中的以下方法:

-(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event 
{ 
    CGPoint location = [self convertTouchToNodeSpace: touch]; 
    sprite.position = location; 
} 
1

请按照以下代码修改您的代码,它正在为我工​​作。

UITouch * touch = [touches anyObject]; 
CGPoint location = [touch locationInView:[touch view]]; 
location = [[CCDirector sharedDirector] convertToGL:location]; 
if (CGRectContainsPoint(sprite.boundingBox,location)){ 
    [sprite setPosition:location]; 

}