Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I tried using the MoveTo method in cocos2d to get a sprite to continuously follow my player sprite:

CCMoveTo actionMove = CCMoveTo.action(actualDuration, player.getPosition());
CCSequence actions = CCSequence.actions(actionMove);
enemy_sprite.runAction(actions);

However when the sprite spawns it just goes to the position the player sprite was at when it spawned, therefore it doesn't follow it continuously. So I tried using a recursive function to get the sprite to follow the player sprite continuously:

CCMoveTo actionMove = CCMoveTo.action(actualDuration, player.getPosition());
CCCallFuncN actionMoveDone = CCCallFuncN.action(this, "enemySpriteMoveFinished");
CCSequence actions = CCSequence.actions(actionMove, actionMoveDone);
enemy_sprite.runAction(actions);

Where "enemySpriteMoveFinished" is:

    public void enemySpriteMoveFinished(Object sender) {
    CCSprite sprite = (CCSprite)sender;
    CCMoveTo actionMove = CCMoveTo.action(0.5f, player.getPosition());
    CCCallFuncN actionMoveDone = CCCallFuncN.action(this, "enemySpriteMoveFinished");
    CCSequence actions = CCSequence.actions(actionMove, actionMoveDone);
    sprite.runAction(actions);
    }

But this method turns out to be rather choppy. Anyone have any solution to getting cocos2d to move a sprite to a dynamic position continuously that's smoother?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

I found out how to do it by updating the enemy sprite in my games update method by adding a fraction of the distance between the enemy sprite and player sprite to the enemy sprites position.

for (CCSprite enemySprite : _enemySprites) {
        CGPoint enemySpritePosition = enemySprite.getPosition();
        CGRect enemySpriteRect = CGRect.make(enemySprite.getPosition().x - (enemySprite.getContentSize().width),
                enemySprite.getPosition().y - (enemySprite.getContentSize().height),
                enemySprite.getContentSize().width,
                enemySprite.getContentSize().height);

        if (CGRect.intersects(playerRect, enemySpriteRect))
            CCDirector.sharedDirector().replaceScene(GameOverScreen.scene());

        enemySpritePosition.x += (player.getPosition().x - enemySprite.getPosition().x) / 50;
        enemySpritePosition.y += (player.getPosition().y - enemySprite.getPosition().y) / 50;
        enemySprite.setPosition(enemySpritePosition.x, enemySpritePosition.y);
    }
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.