2014-02-19 58 views
0

到目前爲止,我已經使用CCActionMoveTo將我的CCSprite移動到用戶在屏幕上的觸摸位置,但是我只有在用戶簡單點擊時才能使用它。CCSprite跟隨用戶觸摸

我希望CCSprite在用戶拖動手指時移動,而不是隨着用戶拖動方向改變方向一起輕敲和移動方向 - 我對cocos2d相當陌生,並且搜索類似的問題但一直無法找到任何。我已經發布了我的代碼如下:

- (id)init 
{ 
    self = [super init]; 
    if (!self) return(nil); 
    self.userInteractionEnabled = YES; 
    // Player sprite 
    _playerSprite = [CCSprite spriteWithImageNamed:@"PlayerSprite.png"]; 
    _playerSprite.scale = 0.5; 
    _playerSprite.position = ccp(self.contentSize.width/2, 150); 
    [self addChild:_playerSprite]; 
    return self; 
} 

-(void) touchBegan:(UITouch *)touch withEvent:(UIEvent *)event { 
    CGPoint touchLoc = [touch locationInNode:self]; 
    CCActionMoveTo *actionMove = [CCActionMoveTo actionWithDuration:0.2f position:ccp(touchLoc.x, 150)]; 
    [_playerSprite runAction:actionMove]; 
} 

回答

0

您將需要實現touchMoved方法並在那裏設置你的精靈位置。事情是這樣的:

- (void)touchMoved:(UITouch *)touch withEvent:(UIEvent *)event { 
    CGPoint touchLocation = [touch locationInNode:self]; 
    _playerSprite.position = touchLocation; 
} 
+0

完美的作品,謝謝!知道這很容易。在精靈移動之前,有什麼方法將運動延遲一秒左右? –

+0

隨着這些事情一直髮射,你需要小心,但你可以創建一個延遲時間的動作序列。 – microslop

0

試試這個(添加CGPoint屬性調用previousTouchPos):

-(void) touchBegan:(UITouch *)touch withEvent:(UIEvent *)event 
{ 
    CGPoint touchLoc = [touch locationInNode:self]; 
    self.previousTouchPos = touchLoc; 

    CCActionMoveTo *actionMove = [CCActionMoveTo actionWithDuration:1.0f position:touchLoc]; 
    [_playerSprite runAction:actionMove]; 
} 


-(void) touchMoved:(UITouch *)touch withEvent:(UIEvent *)event 
{ 
    CGPoint touchLoc = [touch locationInNode:self]; 
    CGPoint delta = ccpSub(touchLoc, self.previousTouchPos); 

    _playerSprite.position = ccpAdd(_playerSprite.position, delta); 
    self.previousTouchPos = touchLoc; 

}