CCSprite关注用户触摸

时间:2014-02-19 17:47:28

标签: iphone cocos2d-iphone

到目前为止,我已经使用CCSpriteCCActionMoveTo移动到屏幕上用户触摸的位置,但是当用户只是点击时我只能使用它。

我希望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];
}

3 个答案:

答案 0 :(得分:0)

您需要实现touchMoved方法并在那里设置精灵位置。像这样:

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

答案 1 :(得分:0)

试试这个(添加名为previousTouchPos的CGPoint属性):

-(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;

}

答案 2 :(得分:0)

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

https://www.makegameswith.us/gamernews/365/make-two-nodes-follow-each-other-in-cocos2d-30

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