代码之家  ›  专栏  ›  技术社区  ›  Daniel Bramhall

CCSprite跟随用户触摸

  •  0
  • Daniel Bramhall  · 技术社区  · 10 年前

    到目前为止,我已经 CCSprite 使用 CCActionMoveTo 然而,我只有在用户简单地点击时才能使用它。

    我希望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 回复  |  直到 10 年前
        1
  •  0
  •   microslop    10 年前

    您需要实现touchMoved方法并在其中设置精灵位置。类似于:

    - (void)touchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
      CGPoint touchLocation = [touch locationInNode:self];
      _playerSprite.position = touchLocation;
    }
    
        2
  •  0
  •   Allen S    10 年前

    尝试此操作(添加名为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;
    
    }
    
        3
  •  0
  •   Ben-G    10 年前

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

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

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