Search code examples
pythonchipmunkpymunk

top down friction in pymunk


Been struggling with this for a couple of days, hard to find code examples on the net.

I'm making a topdown game and having trouble getting the player to move on key press. At the moment i'm using add_force or add_impulse to move the player in a direction, but the player doesn't stop. I've read about using surface friction between the space and the player to simulate friction and here is how it's done in the tank.c demo.

However I don't understand the API enough to port this code from chipmunk into pymunk.

cpConstraint *pivot = cpSpaceAddConstraint(space, cpPivotJointNew2(tankControlBody, tankBody, cpvzero, cpvzero));

So far, I have something that looks like this:

class Player(PhysicalObject):
    BASE_SPEED = 5
    VISIBLE_RANGE = 400
    def __init__(self, image, position, world, movementType=None):
        PhysicalObject.__init__(self, image, position, world)
        self.mass = 100
        self.CreateBody()
        self.controlBody = pymunk.Body(pymunk.inf, pymunk.inf)
        self.joint = pymunk.PivotJoint(self.body, self.controlBody, (0,0))
        self.joint.max_force = 100
        self.joint.bias_coef = 0
        world.space.add(self.joint)

I don't know how to add the constraint of the space/player to the space.

(Need someone with 1500+ rep to create a pymunk tag for this question).


Solution

  • Joe crossposted the question to the Chipmunk/pymunk forum, and it got a couple of more answers there. http://www.slembcke.net/forums/viewtopic.php?f=1&t=1450&start=0&st=0&sk=t&sd=a

    Ive pasted/edited in parts of my answer from the forum below:

    #As pymunk is python and not C, the constructor to PivotJoint is defined as
    def __init__(self, a, b, *args):
        pass
    
    #and the straight conversion from c to python is
    pivot1 = PivotJoint(tankControlBody, tankBody, Vec2d.zero(), Vec2d.zero())
    # but ofc it works equally well with 0 tuples instead of the zero() methods:
    pivot2 = PivotJoint(tankControlBody, tankBody, (0,0), (0,0))
    
    mySpace.add(pivot1, pivot2)
    

    Depending on if you send in one or two arguments to args, it will either use the cpPivotJointNew or cpPivotJointNew2 method in the C interface to create the joint. The difference between these two methods is that cpPivotJointNew want one pivot point as argument, and the cpPivotJointNew2 want two anchor points. So, if you send in one Vec2d pymunk will use cpPivotJointNew, but if you send in two Vec2d it will use cpPivotJointNew2.

    Full PivotJoint constructor documentation is here: PivotJoint constructor docs