0
votes

I am new to cocos2d and I am reading a lot of tutorial What I'd like to do is touch into screen e have the sprite follow my touch. When release touch, the sprite stop When touch far from sprite, the sprite should start moving even if I move continuosly my finger. How I can do this?

I try in different way:

-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    isMoving = YES;
    [self schedule:@selector(moveSprite:)];
    return YES;
}

-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
    isMoving = NO;
    [self unschedule:@selector(moveSprite:)];
}

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
    if (isMoving)
    {
        touchLocation = [touch locationInView: [touch view]];
        touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];
        touchLocation = [self convertToNodeSpace:touchLocation];
    }
}

-(void)moveSprite:(ccTime) dt {

    CGPoint moveVector = ccpSub(touchLocation, mySprite.position);

    float distanceToMove = ccpLength(moveVector);
    float velo = 480.0/3.0;
    float moveDuration = distanceToMove / velo;

    self.moveAction = [CCSequence actions:
                       [CCMoveTo actionWithDuration:moveDuration position:touchLocation],
                       nil
                       ];

    [mySprite runAction:_moveAction];   

}

or again with:

- (void)handlePanFrom:(UIPanGestureRecognizer *)recognizer {

    CGPoint touchLocation = [recognizer locationInView:recognizer.view];
    touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
    touchLocation = [self convertToNodeSpace:touchLocation];                

    moveAction = [CCSequence actions:
                       [CCMoveTo actionWithDuration:2.0f position:touchLocation],
                       nil
                       ];

    [mySprite runAction:moveAction];
}

or simple

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event 
{    
    touchLocation = [touch locationInView: [touch view]];       
    touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];
    touchLocation = [self convertToNodeSpace:touchLocation];

    [_mySprite stopAction:_moveAction];
    _moveAction = [CCMoveTo actionWithDuration:1 position:touchLocation];
    [_mySprite runAction:_moveAction];
}

Can someone help? Thanks a lot!

1
Third one looks to me like it ought to work. What's it actually doing?lins314159

1 Answers

0
votes

The third is not working well, the movement is not smooth even if I check 'moveDuration' and put it inside the action