6
\$\begingroup\$

i'm using cocos2d to build an iphone game.

my game currently has two sprites: one for the main character and another for an item i should carry once he gets on him.

the main character and the item are both box2d bodies. i can detect the collision between the two. what is want is to make the item body stick to the main character body when they meet, that way any movement of the main character would also affect the item.

any suggestions on how to implement this?

thanks!

\$\endgroup\$

2 Answers 2

5
\$\begingroup\$

There has been a lot of discussion on this very topic on the Box2D forums. You'll find most of the info under the guise of breakable bodies, which is your problem in reverse. Here are my suggestions in order of easiness:

  1. Depending on the situation you could just change the animation of the main character to show that he is now carrying the item without needing the item to still be physically simulated.

  2. If that isn't enough, add a new b2Shape to the main characters b2Body. The new shape will look exactly like the shape used in the item and be attached right where you need it.

  3. Lastly, you can use the new weld joint to attach the item to the main character. Note, a weld joint is more like a rubber cement joint. If you want the item to fixed securely in place, use option 2.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Pay particular attention to #3. The joint is not fixed, the physics engine will do its best to keep it in place but it is by no means rigid. If you indeed want it to be part of the character you're way better of with 2 or 1. \$\endgroup\$
    – Kaj
    Aug 25, 2010 at 4:40
  • 1
    \$\begingroup\$ #2 is the officially recommended way too \$\endgroup\$ Aug 25, 2010 at 9:38
2
\$\begingroup\$

I'm not familiar with Box2d in particular, but most physics engines implement the concept of a joint. You create a joint of the appropriate type, attach it to the bodies and presto! they move only in ways allowed by the joint.

\$\endgroup\$
1
  • \$\begingroup\$ This is not quite correct. They will move in ways allowed by the joint unless obstructed. Rigid joints are rarely rigid, and can get pretty unstable when under stress. Try running into a wall with the part attached by the joint, it will either break, stop you, or explode your sim depending on the engine. \$\endgroup\$
    – Kaj
    Aug 25, 2010 at 4:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .