Alex Moskalev
Alex Moskalev

Reputation: 607

Cocos2d how to make one sprite following another sprite?

I have a maze game that using cocos2d I have one main sprite that can save "friend" sprite Once "friend" sprite collide with main sprite, the "friend" sprite will follow main sprite everywhere. Now I dont know how to make "friend" sprite follow main sprite with static distance and smooth movement. I mean if main sprite going up, "friend" will be at behind the main sprite. If main sprite going left, "friend" sprite will be at right of main sprite. Please help me and share me some code...

Upvotes: 4

Views: 2987

Answers (2)

Jingshao Chen
Jingshao Chen

Reputation: 3485

I have a simple solution kind of working fine. Follow the cocos2d document getting started lesson 2, Your first game. After implement the touch event. Use the following code to set seeker1 to follow cocosGuy:

- (void) nextFrame:(ccTime)dt {

    float dx = cocosGuy.position.x - seeker1.position.x;
    float dy = cocosGuy.position.y - seeker1.position.y;
    float d = sqrt(dx*dx + dy*dy);
    float v = 100;

    if (d >  1) {
        seeker1.position = ccp( seeker1.position.x + dx/d * v *dt, 
                           seeker1.position.y + dy/d * v *dt);
    } else {
        seeker1.position = ccp(cocosGuy.position.x, cocosGuy.position.y);
    }
   }

The idea is at every step, the follower just need to move towards the leader at a certain speed. The direction towards the leader can be calculated by shown in the code.

Upvotes: 1

kostja
kostja

Reputation: 61558

You can implement the following behaviour by using the position of your main sprite as the target for the friend sprite. This would involve implementing separation (maintaining a min distance), cohesion (maintaining max distance) and easing (to make the movement smooth).

The exact algorithms (and some more) are detailed in a wonderful behavior animation paper by Craig Reynolds. There are also videos of the individual features and example source code (in C++).

The algorithm you need (it is a combination of multiple simpler ones) is Leader following

EDIT : I have found two straightforward implementations of the algorithms mentioned in the paper with viewable source code here and here. You will need to slightly recombine them from flocking (which is mostly following a centroid) to following a single leader. The language is Processing, resembling java-like pseudcode, so I hope the comprehension should be no problem. The C++ sourcecode I mentioned earlier is also downloadable but does not explicitly feature leader following.
I am not aware of any cocos2d implementations out there.

Upvotes: 4

Related Questions