2011-03-21 22 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]; 

}