Cocos2d how to make one sprite after another sprite?

I have a maze game that uses cocos2d. I have one main sprite that can save the friend sprite. When the friend sprite collides with the main sprite, the friend sprite will follow the main sprite everywhere. Now I do not know how to make a β€œfriend” sprite, following the main sprite with a static distance and smooth movement. I mean, if the main sprite grows, the β€œfriend” will be behind the main sprite. If the main sprite is on the left, the friend sprite will be on the right of the main sprite. Please help me and share me the code ...

+4
source share
2 answers

You can implement the following behavior using the position of your main sprite as a target for friends sprite. This will include performing separation (maintaining a minimum distance), traction (maintaining a maximum distance), and weakening (to make the movement smooth).

Exact algorithms (and some others) are described in detail in Craig Reynolds' remarkable animation work . There is also a video with separate functions and sample source code (in C ++).

The algorithm you need (this is a combination of a few simpler ones), Leader following

EDIT : I found two simple implementations of the algorithms mentioned in the article, with visible source code here and here . You will need to recombine them a bit from the runoff (which is mainly after the centroid) in order to follow one leader. The language is Processing, resembling a java-like pseudo-code, so I hope that understanding should not be a problem. C ++ source code . I mentioned earlier, can also be downloaded, but clearly does not contain a leader.
I do not know about any cocos2d implementations.

+3
source

I have a simple solution that works perfectly. Follow the cocos2d document starting lesson 2, your first game . After performing a 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 needs to move to the leader with a certain speed. The direction to the leader can be calculated as shown in the code.

+1
source

Source: https://habr.com/ru/post/1382450/


All Articles