Search code examples
pythonshapespymunk

How to make "compound" shapes in pymunk?


As the title says, How can I join/constraint 2 pymunk bodies/shapes so that they don't they act as one single object??
For example, in this case, I have a cricket bat, made up of 2 separate bodies and polys.
I want to join the bat's "handle" to my bat's "blade", So that I get a bat-like object.

My code:

### BAT n Co. ###
# body format: [vertices, offset, position, mass]
bat_bodies_v = [
# bat
    [[[0, 34], [4, 34], [4, 0], [0, 0]],(-2,-20),(103,190),20], # handle
    [[[6, 90] , [0, 32] , [0, 17], [6, 0] , [10, 0], [10, 90]],(-5,-20),(100,100),1100] # blade
]

bat_bodies = []
for vertices, offset, pos, mass in bat_bodies_v:
    moment = pm.moment_for_poly(mass,vertices,offset)
    b = pm.Body(mass,moment)
    b.position = pos

    poly = pm.Poly(b, vertices,offset)
    poly.friction = 0.9

    bat_bodies.append(poly)
    space.add(b,poly)

# the closest I got.
j1 = pm.constraint.PinJoint(bat_bodies[0].body,bat_bodies[1].body)
j2 = pm.constraint.RotaryLimitJoint(bat_bodies[0].body,bat_bodies[1].body,0,0)
space.add(j1,j2)

This ============= becomes ================> This StartEnd
I have a function that drew those green circles at the body positions


Solution

  • The best way to build a complex shape in pymunk is simply to attach the shapes to the same body. So unless you have a good reason why you want them separate I suggest you try and add both shapes to the same body.

    However, sometimes you might want to do something else, for example be able to break the objects. I havent really implmented anything myself, but Scott (of Chipmunk) writes in this post http://chipmunk-physics.net/forum/viewtopic.php?f=1&t=2420&p=10644&hilit=breakable#p10644 that using a PivotJoint and a GearJoint might be a good idea to keep the two bodies together.