Iphone CCSprite跟随用户触摸

Iphone CCSprite跟随用户触摸,iphone,cocos2d-iphone,Iphone,Cocos2d Iphone,到目前为止,我已经使用CCActionMoveTo将我的CCSprite移动到用户触摸屏上的位置,但是我只有在用户简单点击时才能使它工作 我希望CCSprite在用户拖动手指时移动,而不仅仅是轻敲和移动,随着用户拖动方向的改变而改变方向——我对cocos2d相当陌生,搜索过类似的问题,但一直找不到任何问题。我已将我的代码张贴在下面: - (id)init { self = [super init]; if (!self) return(nil); self.userInt

到目前为止,我已经使用
CCActionMoveTo
将我的
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];
}

您需要实现touchMoved方法并在其中设置精灵位置。大概是这样的:

- (void)touchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
  CGPoint touchLocation = [touch locationInNode:self];
  _playerSprite.position = touchLocation;
}
尝试以下操作(添加名为previousTouchPos的CGPoint属性):


这听起来像是CCActionFollow的理想用例:


如果使用通过块提供目标位置的变体,则可以使用最新的触摸位置作为目标位置。

非常有效,谢谢!我知道这很容易。有没有办法在精灵移动之前将移动延迟一秒左右?这些东西一直在发射,你需要小心,但是你可以创建一个延迟时间的动作序列。
-(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;

}