Search code examples
pythonpymunk

pymunk - Is there a standard way to set custom gravity for an object?


The pymunk documentation writes that gravity for a scene "Defaults to (0,0). Can be overridden on a per body basis by writing custom integration functions." How would you write the custom integration functions to change gravity for an object (for example, if I have an object on a ladder I want its gravity to be 0, but otherwise I want gravity for that scene to exist)? If it makes a difference, I'm still on python 2.


Solution

  • You can do it by writing your own velocity function and set it on the body of the object you want custom gravity on.

    >>> import pymunk
    >>> space = pymunk.Space()
    >>> space.gravity = 0, 10
    >>> body = pymunk.Body(1,2)
    >>> space.add(body)
    >>> def zero_gravity(body, gravity, damping, dt):
    ...     pymunk.Body.update_velocity(body, (0,0), damping, dt)
    ... 
    >>> body.velocity_func = zero_gravity
    >>> space.step(1)
    >>> space.step(1)
    >>> print(body.position, body.velocity)
    Vec2d(0.0, 0.0) Vec2d(0.0, 0.0)
    

    The velocity function is documented here: http://www.pymunk.org/en/latest/pymunk.html#pymunk.Body.velocity_func