Reputation: 798
That's my goal: I have multiple sprites that makes the personage. The first sprite (on an array of n sprites, where n is the number of segments) is the head and the other sprites must follow that. So, If the head change his angle and then moves (in the direction where the head is pointing), the other sprites must follow the head, like a snake/worm does. I'm doing this with cocos2D but is not that relevant because I think that I don't have the concept, because I know cocos2D, but is not this the problem (not the framework). So, how can I do it? How can the other sprites follow perfectly the head? Game examples are Death Worm or Super Mega Worm on App Store
If needed, I can post the code that I'm using (works bad) and an image of the result, but I don't know if this is needed.
Thanks.
Upvotes: 0
Views: 1851
Reputation: 1053
I would simply store all the positions of each section in an arraylist / vector. on Draw have the next head position calculated based on game play then remove the oldest (pos==0) item in the list and draw the sprites at the positions in the list.
I'm sorry if this seems similar to Alexey's answer, I just think this might be a simpler implementation.
Upvotes: 1
Reputation: 62106
Have an array of coordinates for every segment of the critter, including the head.
If it needs to move straight (not changing the direction), you shift the array values so the tail (last) segment gets the coordinates of the adjacent segment, that one gets the coordinates of the one before it and so on and for the head segment you set the new head coordinates, which are equal to old coordinates incremented by the direction vector d:
dx dy direction
0 -1 up
0 +1 down
-1 0 left
+1 0 right
If you want to change the direction, change the direction vector appropriately and then do the same array shift and head coordinate update.
Upvotes: 0
Reputation: 5546
You will need to manually set the positions of every sprite that makes the personage. The new position has to be calculated and set inside the scheduled method that gets called repeatedly.
sprite.position = ccp(newX,newY);
You may refer this too: Cocos2D set sprite position in relation to another sprite
Upvotes: 0