API Reference

pymunk Package

pymunk

pymunk is a easy-to-use pythonic 2d physics library that can be used whenever you need 2d rigid body physics from Python.

Homepage: http://www.pymunk.org

This is the main containing module of pymunk. It contains among other things the very central Space, Body and Shape classes.

When you import this module it will automatically load the chipmunk library file. As long as you haven’t turned off the debug mode a print will show exactly which Chipmunk library file it loaded. For example:

>>> import pymunk
Loading chipmunk for Windows (32bit) [C:\code\pymunk\chipmunk.dll]
pymunk.inf = 1e+100

Infinity that can be passed as mass or inertia to Body.

Useful when you for example want a body that cannot rotate, just set its moment to inf. Just remember that if two objects with both infinite masses collides the world might explode. Similary effects can happen with infinite moment.

Note

In previous versions of pymunk you used inf to create static bodies. This has changed and you should instead do it by invoking the body constructor without any arguments.

pymunk.version = '4.0.0'

The release version of this pymunk installation. Valid only if pymunk was installed from a source or binary distribution (i.e. not in a checked-out copy from svn).

pymunk.chipmunk_version = '<Mock object at 0x98ea7ec>R3bdf1b7b3c'

The Chipmunk version compatible with this pymunk version. Other (newer) Chipmunk versions might also work if the new version does not contain any breaking API changes.

This property does not show a valid value in the compiled documentation, only when you actually import pymunk and do pymunk.chipmunk_version

The string is in the following format: <cpVersionString>R<svn or github commit of chipmunk> where cpVersionString is a version string set by Chipmunk and the svn version corresponds to the svn version of the chipmunk source files included with pymunk or the github commit hash. If the Chipmunk version is a release then the second part will be empty

Note

This is also the version of the Chipmunk source files included in the chipmunk_src folder (normally included in the pymunk source distribution).

class pymunk.Space(iterations=10)[source]

Bases: object

Spaces are the basic unit of simulation. You add rigid bodies, shapes and joints to it and then step them all forward together through time.

__init__(iterations=10)[source]

Create a new instace of the Space

Its usually best to keep the elastic_iterations setting to 0. Only change if you have problem with stacking elastic objects on each other. If that is the case, try to raise it. However, a value other than 0 will affect other parts, most importantly you wont get reliable total_impulse readings from the Arbiter object in collsion callbacks!

Parameters :
iterations : int

Number of iterations to use in the impulse solver to solve contacts.

add(*objs)[source]

Add one or many shapes, bodies or joints to the space

Unlike Chipmunk and earlier versions of pymunk its now allowed to add objects even from a callback during the simulation step. However, the add will not be performed until the end of the step.

add_collision_handler(a, b, begin=None, pre_solve=None, post_solve=None, separate=None, *args, **kwargs)[source]

Add a collision handler for given collision type pair.

Whenever a shapes with collision_type a and collision_type b collide, these callbacks will be used to process the collision. None can be provided for callbacks you do not wish to implement, however pymunk will call it’s own default versions for these and not the default ones you’ve set up for the Space. If you need to fall back on the space’s default callbacks, you’ll have to provide them individually to each handler definition.

Parameters :
a : int

Collision type of the first shape

b : int

Collision type of the second shape

begin : func(space, arbiter, *args, **kwargs) -> bool

Collision handler called when two shapes just started touching for the first time this step. Return false from the callback to make pymunk ignore the collision or true to process it normally. Rejecting a collision from a begin() callback permanently rejects the collision until separation. Pass None if you wish to use the pymunk default.

pre_solve : func(space, arbiter, *args, **kwargs) -> bool

Collision handler called when two shapes are touching. Return false from the callback to make pymunk ignore the collision or true to process it normally. Additionally, you may override collision values such as Arbiter.elasticity and Arbiter.friction to provide custom friction or elasticity values. See Arbiter for more info. Pass None if you wish to use the pymunk default.

post_solve : func(space, arbiter, *args, **kwargs)

Collsion handler called when two shapes are touching and their collision response has been processed. You can retrieve the collision force at this time if you want to use it to calculate sound volumes or damage amounts. Pass None if you wish to use the pymunk default.

separate : func(space, arbiter, *args, **kwargs)

Collision handler called when two shapes have just stopped touching for the first time this frame. Pass None if you wish to use the pymunk default.

args

Optional parameters passed to the collision handler functions.

kwargs

Optional keyword parameters passed on to the collision handler functions.

add_post_step_callback(callback_function, obj, *args, **kwargs)[source]

Add a function to be called last in the next simulation step.

Post step callbacks are registered as a function and an object used as a key. You can only register one post step callback per object.

This function was more useful with earlier versions of pymunk where you weren’t allowed to use the add and remove methods on the space during a simulation step. But this function is still available for other uses and to keep backwards compatibility.

Note

If you remove a shape from the callback it will trigger the collision handler for the ‘separate’ event if it the shape was touching when removed.

Parameters :
callback_function : func(obj, *args, **kwargs)

The callback function.

obj : Any object

This object is used as a key, you can only have one callback for a single object. It is passed on to the callback function.

args

Optional parameters passed to the callback function.

kwargs

Optional keyword parameters passed on to the callback function.

Return :

True if key was not previously added, False otherwise

bb_query(bb, layers=-1, group=0)[source]

Perform a fast rectangle query on the space.

Only the shape’s bounding boxes are checked for overlap, not their full shape. Returns a list of shapes.

bodies

A list of the bodies added to this space

collision_bias

Determines how fast overlapping shapes are pushed apart.

Expressed as a fraction of the error remaining after each second. Defaults to pow(1.0 - 0.1, 60.0) meaning that pymunk fixes 10% of overlap each frame at 60Hz.

collision_persistence

Number of frames that contact information should persist.

Defaults to 3. There is probably never a reason to change this value.

collision_slop

Amount of allowed penetration.

Used to reduce oscillating contacts and keep the collision cache warm. Defaults to 0.1. If you have poor simulation quality, increase this number as much as possible without allowing visible amounts of overlap.

constraints

A list of the constraints added to this space

damping

Damping rate expressed as the fraction of velocity bodies retain each second.

A value of 0.9 would mean that each body’s velocity will drop 10% per second. The default value is 1.0, meaning no damping is applied.

enable_contact_graph

Rebuild the contact graph during each step.

Must be enabled to use the get_arbiter() function on Body Disabled by default for a small performance boost. Enabled implicitly when the sleeping feature is enabled.

gravity

Default gravity to supply when integrating rigid body motions.

idle_speed_threshold

Speed threshold for a body to be considered idle. The default value of 0 means to let the space guess a good threshold based on gravity.

iterations

Number of iterations to use in the impulse solver to solve contacts.

nearest_point_query(point, max_distance, layers=-1, group=0)[source]

Query space at point filtering out matches with the given layers and group. Return a list of all shapes within max_distance of the point.

If you don’t want to filter out any matches, use -1 for the layers and 0 as the group.

Parameters :
point : (x,y) or Vec2d

Define where to check for collision in the space.

max_distance : int

Maximumm distance of shape from point

layers : int

Only pick shapes matching the bit mask. i.e. (layers & shape.layers) != 0

group : int

Only pick shapes not in this group.

Return :

[dict(shape=`Shape`, distance = distance, point = Vec2d)]

nearest_point_query_nearest(point, max_distance, layers=-1, group=0)[source]

Query space at point filtering out matches with the given layers and group. Return nearest of all shapes within max_distance of the point.

If you don’t want to filter out any matches, use -1 for the layers and 0 as the group.

Parameters :
point : (x,y) or Vec2d

Define where to check for collision in the space.

max_distance : int

Maximumm distance of shape from point

layers : int

Only pick shapes matching the bit mask. i.e. (layers & shape.layers) != 0

group : int

Only pick shapes not in this group.

Return :

dict(shape=`Shape`, distance = distance, point = Vec2d)

point_query(point, layers=-1, group=0)[source]

Query space at point filtering out matches with the given layers and group. Return a list of found shapes.

If you don’t want to filter out any matches, use -1 for the layers and 0 as the group.

Parameters :
point : (x,y) or Vec2d

Define where to check for collision in the space.

layers : int

Only pick shapes matching the bit mask. i.e. (layers & shape.layers) != 0

group : int

Only pick shapes not in this group.

point_query_first(point, layers=-1, group=0)[source]

Query space at point and return the first shape found matching the given layers and group. Returns None if no shape was found.

Parameters :
point : (x,y) or Vec2d

Define where to check for collision in the space.

layers : int

Only pick shapes matching the bit mask. i.e. (layers & shape.layers) != 0

group : int

Only pick shapes not in this group.

reindex_shape(shape)[source]

Update the collision detection data for a specific shape in the space.

reindex_static()[source]

Update the collision detection info for the static shapes in the space. You only need to call this if you move one of the static shapes.

remove(*objs)[source]

Remove one or many shapes, bodies or constraints from the space

Unlike Chipmunk and earlier versions of pymunk its now allowed to remove objects even from a callback during the simulation step. However, the removal will not be performed until the end of the step.

Note

When removing objects from the space, make sure you remove any other objects that reference it. For instance, when you remove a body, remove the joints and shapes attached to it.

remove_collision_handler(a, b)[source]

Remove a collision handler for a given collision type pair.

Parameters :
a : int

Collision type of the first shape

b : int

Collision type of the second shape

segment_query(start, end, layers=-1, group=0)[source]

Query space along the line segment from start to end filtering out matches with the given layers and group.

Segment queries are like ray casting, but because pymunk uses a spatial hash to process collisions, it cannot process infinitely long queries like a ray. In practice this is still very fast and you don’t need to worry too much about the performance as long as you aren’t using very long segments for your queries.

Return :[SegmentQueryInfo] - One SegmentQueryInfo object for each hit.
segment_query_first(start, end, layers=-1, group=0)[source]

Query space along the line segment from start to end filtering out matches with the given layers and group. Only the first shape encountered is returned and the search is short circuited. Returns None if no shape was found.

set_default_collision_handler(begin=None, pre_solve=None, post_solve=None, separate=None, *args, **kwargs)[source]

Register a default collision handler to be used when no specific collision handler is found. If you do nothing, the space will be given a default handler that accepts all collisions in begin() and pre_solve() and does nothing for the post_solve() and separate() callbacks.

Parameters :
begin : func(space, arbiter, *args, **kwargs) -> bool

Collision handler called when two shapes just started touching for the first time this step. Return False from the callback to make pymunk ignore the collision or True to process it normally. Rejecting a collision from a begin() callback permanently rejects the collision until separation. Pass None if you wish to use the pymunk default.

pre_solve : func(space, arbiter, *args, **kwargs) -> bool

Collision handler called when two shapes are touching. Return False from the callback to make pymunk ignore the collision or True to process it normally. Additionally, you may override collision values such as Arbiter.elasticity and Arbiter.friction to provide custom friction or elasticity values. See Arbiter for more info. Pass None if you wish to use the pymunk default.

post_solve : func(space, arbiter, *args, **kwargs)

Collsion handler called when two shapes are touching and their collision response has been processed. You can retrieve the collision force at this time if you want to use it to calculate sound volumes or damage amounts. Pass None if you wish to use the pymunk default.

separate : func(space, arbiter, *args, **kwargs)

Collision handler called when two shapes have just stopped touching for the first time this frame. Pass None if you wish to use the pymunk default.

args

Optional parameters passed to the collision handler functions.

kwargs

Optional keyword parameters passed on to the collision handler functions.

shape_query(shape)[source]

Query a space for any shapes overlapping the given shape

Returns a list of shapes.

shapes

A list of all the shapes added to this space (both static and non-static)

sleep_time_threshold

Time a group of bodies must remain idle in order to fall asleep.

Enabling sleeping also implicitly enables the the contact graph. The default value of inf disables the sleeping algorithm.

static_body

A convenience static body already added to the space

step(dt)[source]

Update the space for the given time step. Using a fixed time step is highly recommended. Doing so will increase the efficiency of the contact persistence, requiring an order of magnitude fewer iterations to resolve the collisions in the usual case.

class pymunk.Body(mass=None, moment=None)[source]

Bases: object

A rigid body

  • Use forces to modify the rigid bodies if possible. This is likely to be the most stable.
  • Modifying a body’s velocity shouldn’t necessarily be avoided, but applying large changes can cause strange results in the simulation. Experiment freely, but be warned.
  • Don’t modify a body’s position every step unless you really know what you are doing. Otherwise you’re likely to get the position/velocity badly out of sync.
__init__(mass=None, moment=None)[source]

Create a new Body

To create a static body, pass in None for mass and moment.

activate()[source]

Wake up a sleeping or idle body.

angle

The rotation of the body.

Note

If you get small/no changes to the angle when for example a ball is “rolling” down a slope it might be because the Circle shape attached to the body or the slope shape does not have any friction set.

angular_velocity
angular_velocity_limit
apply_force(f, r=(0, 0))[source]

Apply (accumulate) the force f on body at a relative offset (important!) r from the center of gravity.

Both r and f are in world coordinates.

Parameters :
f : (x,y) or Vec2d

Force in world coordinates

r : (x,y) or Vec2d

Offset in world coordinates

apply_impulse(j, r=(0, 0))[source]

Apply the impulse j to body at a relative offset (important!) r from the center of gravity. Both r and j are in world coordinates.

Parameters :
j : (x,y) or Vec2d

Impulse to be applied

r : (x,y) or Vec2d

Offset the impulse with this vector

constraints

Get the constraints this body is attached to.

each_arbiter(func, *args, **kwargs)[source]

Run func on each of the arbiters on this body.

func(arbiter, *args, **kwargs) -> None

Callback Parameters
arbiter : Arbiter
The Arbiter
args
Optional parameters passed to the callback function.
kwargs
Optional keyword parameters passed on to the callback function.

Warning

Do not hold on to the Arbiter after the callback!

force
is_rogue

Returns true if the body has not been added to a space.

is_sleeping

Returns true if the body is sleeping.

is_static

Returns true if the body is a static body

kinetic_energy

Get the kinetic energy of a body.

local_to_world(v)[source]

Convert body local coordinates to world space coordinates

Parameters :
v : (x,y) or Vec2d

Vector in body local coordinates

mass
moment
position
position_func

The position callback function. The position callback function is called each time step and can be used to update the body’s position.

func(body, dt) -> None

Callback Parameters
body : Body
Body that should have its velocity calculated
dt : float
Delta time since last step.
reset_forces()[source]

Zero both the forces and torques accumulated on body

rotation_vector
shapes

Get the shapes attached to this body.

sleep()[source]

Force a body to fall asleep immediately.

sleep_with_group(body)[source]

Force a body to fall asleep immediately along with other bodies in a group.

torque
static update_position(body, dt)[source]

Default rigid body position integration function.

Updates the position of the body using Euler integration. Unlike the velocity function, it’s unlikely you’ll want to override this function. If you do, make sure you understand it’s source code (in Chipmunk) as it’s an important part of the collision/joint correction process.

static update_velocity(body, gravity, damping, dt)[source]

Default rigid body velocity integration function.

Updates the velocity of the body using Euler integration.

velocity
velocity_func

The velocity callback function. The velocity callback function is called each time step, and can be used to set a body’s velocity.

func(body, gravity, damping, dt) -> None

Callback Parameters
body : Body
Body that should have its velocity calculated
gravity : Vec2d
The gravity vector
damping : float
The damping
dt : float
Delta time since last step.
velocity_limit
world_to_local(v)[source]

Convert world space coordinates to body local coordinates

Parameters :
v : (x,y) or Vec2d

Vector in world space coordinates

class pymunk.Shape(shape=None)[source]

Bases: object

Base class for all the shapes.

You usually dont want to create instances of this class directly but use one of the specialized shapes instead.

__init__(shape=None)[source]
bb

The bounding box of the shape. Only guaranteed to be valid after Shape.cache_bb() or Space.step() is called. Moving a body that a shape is connected to does not update it’s bounding box. For shapes used for queries that aren’t attached to bodies, you can also use Shape.update().

body

The body this shape is attached to. Can be set to None to indicate that this shape doesnt belong to a body.

cache_bb()[source]

Update and returns the bouding box of this shape

collision_type

User defined collision type for the shape. See add_collisionpair_func function for more information on when to use this property

elasticity

Elasticity of the shape. A value of 0.0 gives no bounce, while a value of 1.0 will give a ‘perfect’ bounce. However due to inaccuracies in the simulation using 1.0 or greater is not recommended.

friction

Friction coefficient. pymunk uses the Coulomb friction model, a value of 0.0 is frictionless.

A value over 1.0 is perfectly fine.

Some real world example values from wikipedia (Remember that it is what looks good that is important, not the exact value).

Material Other Friction
Aluminium Steel 0.61
Copper Steel 0.53
Brass Steel 0.51
Cast iron Copper 1.05
Cast iron Zinc 0.85
Concrete (wet) Rubber 0.30
Concrete (dry) Rubber 1.0
Concrete Wood 0.62
Copper Glass 0.68
Glass Glass 0.94
Metal Wood 0.5
Polyethene Steel 0.2
Steel Steel 0.80
Steel Teflon 0.04
Teflon (PTFE) Teflon 0.04
Wood Wood 0.4
group

Shapes in the same non-zero group do not generate collisions. Useful when creating an object out of many shapes that you don’t want to self collide. Defaults to 0

layers

Shapes only collide if they are in the same bit-planes. i.e. (a.layers & b.layers) != 0. By default, a shape occupies all 32 bit-planes, i.e. layers == -1

point_query(p)[source]

Check if the given point lies within the shape.

segment_query(start, end)[source]

Check if the line segment from start to end intersects the shape.

Return either SegmentQueryInfo object or None

sensor

A boolean value if this shape is a sensor or not. Sensors only call collision callbacks, and never generate real collisions.

surface_velocity

The surface velocity of the object. Useful for creating conveyor belts or players that move around. This value is only used when calculating friction, not resolving the collision.

update(position, rotation_vector)[source]

Update, cache and return the bounding box of a shape with an explicit transformation.

Useful if you have a shape without a body and want to use it for querying.

class pymunk.Circle(body, radius, offset=(0, 0))[source]

Bases: pymunk.Shape

A circle shape defined by a radius

This is the fastest and simplest collision shape

__init__(body, radius, offset=(0, 0))[source]

body is the body attach the circle to, offset is the offset from the body’s center of gravity in body local coordinates.

It is legal to send in None as body argument to indicate that this shape is not attached to a body.

bb

The bounding box of the shape. Only guaranteed to be valid after Shape.cache_bb() or Space.step() is called. Moving a body that a shape is connected to does not update it’s bounding box. For shapes used for queries that aren’t attached to bodies, you can also use Shape.update().

body

The body this shape is attached to. Can be set to None to indicate that this shape doesnt belong to a body.

cache_bb()

Update and returns the bouding box of this shape

collision_type

User defined collision type for the shape. See add_collisionpair_func function for more information on when to use this property

elasticity

Elasticity of the shape. A value of 0.0 gives no bounce, while a value of 1.0 will give a ‘perfect’ bounce. However due to inaccuracies in the simulation using 1.0 or greater is not recommended.

friction

Friction coefficient. pymunk uses the Coulomb friction model, a value of 0.0 is frictionless.

A value over 1.0 is perfectly fine.

Some real world example values from wikipedia (Remember that it is what looks good that is important, not the exact value).

Material Other Friction
Aluminium Steel 0.61
Copper Steel 0.53
Brass Steel 0.51
Cast iron Copper 1.05
Cast iron Zinc 0.85
Concrete (wet) Rubber 0.30
Concrete (dry) Rubber 1.0
Concrete Wood 0.62
Copper Glass 0.68
Glass Glass 0.94
Metal Wood 0.5
Polyethene Steel 0.2
Steel Steel 0.80
Steel Teflon 0.04
Teflon (PTFE) Teflon 0.04
Wood Wood 0.4
group

Shapes in the same non-zero group do not generate collisions. Useful when creating an object out of many shapes that you don’t want to self collide. Defaults to 0

layers

Shapes only collide if they are in the same bit-planes. i.e. (a.layers & b.layers) != 0. By default, a shape occupies all 32 bit-planes, i.e. layers == -1

offset

Offset. (body space coordinates)

point_query(p)

Check if the given point lies within the shape.

radius

The Radius of the circle

segment_query(start, end)

Check if the line segment from start to end intersects the shape.

Return either SegmentQueryInfo object or None

sensor

A boolean value if this shape is a sensor or not. Sensors only call collision callbacks, and never generate real collisions.

surface_velocity

The surface velocity of the object. Useful for creating conveyor belts or players that move around. This value is only used when calculating friction, not resolving the collision.

unsafe_set_offset(o)[source]

Unsafe set the offset of the circle.

Note

This change is only picked up as a change to the position of the shape’s surface, but not it’s velocity. Changing it will not result in realistic physical behavior. Only use if you know what you are doing!

unsafe_set_radius(r)[source]

Unsafe set the radius of the circle.

Note

This change is only picked up as a change to the position of the shape’s surface, but not it’s velocity. Changing it will not result in realistic physical behavior. Only use if you know what you are doing!

update(position, rotation_vector)

Update, cache and return the bounding box of a shape with an explicit transformation.

Useful if you have a shape without a body and want to use it for querying.

class pymunk.Poly(body, vertices, offset=(0, 0), radius=0)[source]

Bases: pymunk.Shape

A convex polygon shape

Slowest, but most flexible collision shape.

It is legal to send in None as body argument to indicate that this shape is not attached to a body.

__init__(body, vertices, offset=(0, 0), radius=0)[source]

Create a polygon

body : Body
The body to attach the poly to
vertices : [(x,y)] or [Vec2d]
Define a convex hull of the polygon with a counterclockwise winding.
offset : (x,y) or Vec2d
The offset from the body’s center of gravity in body local coordinates.
radius : int
Set the radius of the poly shape.
bb

The bounding box of the shape. Only guaranteed to be valid after Shape.cache_bb() or Space.step() is called. Moving a body that a shape is connected to does not update it’s bounding box. For shapes used for queries that aren’t attached to bodies, you can also use Shape.update().

body

The body this shape is attached to. Can be set to None to indicate that this shape doesnt belong to a body.

cache_bb()

Update and returns the bouding box of this shape

collision_type

User defined collision type for the shape. See add_collisionpair_func function for more information on when to use this property

static create_box(body, size=(10, 10), offset=(0, 0), radius=0)[source]

Convenience function to create a box centered around the body position.

The size is given as as (w,h) tuple.

elasticity

Elasticity of the shape. A value of 0.0 gives no bounce, while a value of 1.0 will give a ‘perfect’ bounce. However due to inaccuracies in the simulation using 1.0 or greater is not recommended.

friction

Friction coefficient. pymunk uses the Coulomb friction model, a value of 0.0 is frictionless.

A value over 1.0 is perfectly fine.

Some real world example values from wikipedia (Remember that it is what looks good that is important, not the exact value).

Material Other Friction
Aluminium Steel 0.61
Copper Steel 0.53
Brass Steel 0.51
Cast iron Copper 1.05
Cast iron Zinc 0.85
Concrete (wet) Rubber 0.30
Concrete (dry) Rubber 1.0
Concrete Wood 0.62
Copper Glass 0.68
Glass Glass 0.94
Metal Wood 0.5
Polyethene Steel 0.2
Steel Steel 0.80
Steel Teflon 0.04
Teflon (PTFE) Teflon 0.04
Wood Wood 0.4
get_vertices()[source]

Get the vertices in world coordinates for the polygon

Returns:[Vec2d] in world coords
group

Shapes in the same non-zero group do not generate collisions. Useful when creating an object out of many shapes that you don’t want to self collide. Defaults to 0

layers

Shapes only collide if they are in the same bit-planes. i.e. (a.layers & b.layers) != 0. By default, a shape occupies all 32 bit-planes, i.e. layers == -1

point_query(p)

Check if the given point lies within the shape.

radius

The radius of the poly shape. Extends the poly in all directions with the given radius

segment_query(start, end)

Check if the line segment from start to end intersects the shape.

Return either SegmentQueryInfo object or None

sensor

A boolean value if this shape is a sensor or not. Sensors only call collision callbacks, and never generate real collisions.

surface_velocity

The surface velocity of the object. Useful for creating conveyor belts or players that move around. This value is only used when calculating friction, not resolving the collision.

unsafe_set_radius(radius)[source]

Unsafe set the radius of the poly.

Note

This change is only picked up as a change to the position of the shape’s surface, but not it’s velocity. Changing it will not result in realistic physical behavior. Only use if you know what you are doing!

unsafe_set_vertices(vertices, offset=(0, 0))[source]

Unsafe set the vertices of the poly.

Note

This change is only picked up as a change to the position of the shape’s surface, but not it’s velocity. Changing it will not result in realistic physical behavior. Only use if you know what you are doing!

update(position, rotation_vector)

Update, cache and return the bounding box of a shape with an explicit transformation.

Useful if you have a shape without a body and want to use it for querying.

class pymunk.Segment(body, a, b, radius)[source]

Bases: pymunk.Shape

A line segment shape between two points

This shape can be attached to moving bodies, but don’t currently generate collisions with other line segments. Can be beveled in order to give it a thickness.

It is legal to send in None as body argument to indicate that this shape is not attached to a body.

__init__(body, a, b, radius)[source]

Create a Segment

Parameters :
body : Body

The body to attach the segment to

a : (x,y) or Vec2d

The first endpoint of the segment

b : (x,y) or Vec2d

The second endpoint of the segment

radius : float

The thickness of the segment

a

The first of the two endpoints for this segment

b

The second of the two endpoints for this segment

bb

The bounding box of the shape. Only guaranteed to be valid after Shape.cache_bb() or Space.step() is called. Moving a body that a shape is connected to does not update it’s bounding box. For shapes used for queries that aren’t attached to bodies, you can also use Shape.update().

body

The body this shape is attached to. Can be set to None to indicate that this shape doesnt belong to a body.

cache_bb()

Update and returns the bouding box of this shape

collision_type

User defined collision type for the shape. See add_collisionpair_func function for more information on when to use this property

elasticity

Elasticity of the shape. A value of 0.0 gives no bounce, while a value of 1.0 will give a ‘perfect’ bounce. However due to inaccuracies in the simulation using 1.0 or greater is not recommended.

friction

Friction coefficient. pymunk uses the Coulomb friction model, a value of 0.0 is frictionless.

A value over 1.0 is perfectly fine.

Some real world example values from wikipedia (Remember that it is what looks good that is important, not the exact value).

Material Other Friction
Aluminium Steel 0.61
Copper Steel 0.53
Brass Steel 0.51
Cast iron Copper 1.05
Cast iron Zinc 0.85
Concrete (wet) Rubber 0.30
Concrete (dry) Rubber 1.0
Concrete Wood 0.62
Copper Glass 0.68
Glass Glass 0.94
Metal Wood 0.5
Polyethene Steel 0.2
Steel Steel 0.80
Steel Teflon 0.04
Teflon (PTFE) Teflon 0.04
Wood Wood 0.4
group

Shapes in the same non-zero group do not generate collisions. Useful when creating an object out of many shapes that you don’t want to self collide. Defaults to 0

layers

Shapes only collide if they are in the same bit-planes. i.e. (a.layers & b.layers) != 0. By default, a shape occupies all 32 bit-planes, i.e. layers == -1

point_query(p)

Check if the given point lies within the shape.

radius

The radius/thickness of the segment

segment_query(start, end)

Check if the line segment from start to end intersects the shape.

Return either SegmentQueryInfo object or None

sensor

A boolean value if this shape is a sensor or not. Sensors only call collision callbacks, and never generate real collisions.

surface_velocity

The surface velocity of the object. Useful for creating conveyor belts or players that move around. This value is only used when calculating friction, not resolving the collision.

unsafe_set_a(a)[source]

Set the first of the two endpoints for this segment

Note

This change is only picked up as a change to the position of the shape’s surface, but not it’s velocity. Changing it will not result in realistic physical behavior. Only use if you know what you are doing!

unsafe_set_b(b)[source]

Set the second of the two endpoints for this segment

Note

This change is only picked up as a change to the position of the shape’s surface, but not it’s velocity. Changing it will not result in realistic physical behavior. Only use if you know what you are doing!

unsafe_set_radius(r)[source]

Set the radius of the segment

Note

This change is only picked up as a change to the position of the shape’s surface, but not it’s velocity. Changing it will not result in realistic physical behavior. Only use if you know what you are doing!

update(position, rotation_vector)

Update, cache and return the bounding box of a shape with an explicit transformation.

Useful if you have a shape without a body and want to use it for querying.

pymunk.moment_for_circle(mass, inner_radius, outer_radius, offset=(0, 0))[source]

Calculate the moment of inertia for a circle

pymunk.moment_for_poly(mass, vertices, offset=(0, 0))[source]

Calculate the moment of inertia for a polygon

pymunk.moment_for_segment(mass, a, b)[source]

Calculate the moment of inertia for a segment

pymunk.moment_for_box(mass, width, height)[source]

Calculate the momentn of inertia for a box

pymunk.reset_shapeid_counter()[source]

Reset the internal shape counter

pymunk keeps a counter so that every new shape is given a unique hash value to be used in the spatial hash. Because this affects the order in which the collisions are found and handled, you should reset the shape counter every time you populate a space with new shapes. If you don’t, there might be (very) slight differences in the simulation.

class pymunk.SegmentQueryInfo(shape, start, end, t, n)[source]

Bases: object

Segment queries return more information than just a simple yes or no, they also return where a shape was hit and it’s surface normal at the hit point. This object hold that information.

__init__(shape, start, end, t, n)[source]

You shouldn’t need to initialize SegmentQueryInfo objects on your own.

get_hit_distance()[source]

Return the absolute distance where the segment first hit the shape

get_hit_point()[source]

Return the hit point in world coordinates where the segment first intersected with the shape

n

Normal of hit surface

shape

Shape that was hit

t

Distance along query segment, will always be in the range [0, 1]

class pymunk.Contact(_contact)[source]

Bases: object

Contact information

__init__(_contact)[source]

Initialize a Contact object from the Chipmunk equivalent struct

Note

You should never need to create an instance of this class directly.

distance

Penetration distance

normal

Contact normal

position

Contact position

class pymunk.Arbiter(_arbiter, space)[source]

Bases: object

Arbiters are collision pairs between shapes that are used with the collision callbacks.

Warning

Because arbiters are handled by the space you should never hold onto a reference to an arbiter as you don’t know when it will be destroyed! Use them within the callback where they are given to you and then forget about them or copy out the information you need from them.

__init__(_arbiter, space)[source]

Initialize an Arbiter object from the Chipmunk equivalent struct and the Space.

Note

You should never need to create an instance of this class directly.

contacts

Information on the contact points between the objects. Return [Contact]

elasticity

Elasticity

friction

Friction

is_first_contact

Returns true if this is the first step that an arbiter existed. You can use this from preSolve and postSolve to know if a collision between two shapes is new without needing to flag a boolean in your begin callback.

shapes

Get the shapes in the order that they were defined in the collision handler associated with this arbiter

stamp

Time stamp of the arbiter. (from the space)

surface_velocity

Used for surface_v calculations, implementation may change

total_impulse

Returns the impulse that was applied this step to resolve the collision.

This property should only be called from a post-solve, post-step

total_impulse_with_friction

Returns the impulse with friction that was applied this step to resolve the collision.

This property should only be called from a post-solve, post-step

total_ke

The amount of energy lost in a collision including static, but not dynamic friction.

This property should only be called from a post-solve, post-step

class pymunk.BB(*args)[source]

Bases: object

Simple bounding box class. Stored as left, bottom, right, top values.

__init__(*args)[source]

Create a new instance of a bounding box. Can be created with zero size with bb = BB() or with four args defining left, bottom, right and top: bb = BB(left, bottom, right, top)

bottom
clamp_vect(v)[source]

Returns a copy of the vector v clamped to the bounding box

contains(other)[source]

Returns true if bb completley contains the other bb

contains_vect(v)[source]

Returns true if this bb contains the vector v

expand(v)[source]

Return the minimal bounding box that contans both this bounding box and the vector v

intersects(other)[source]

Returns true if the bounding boxes intersect

left
merge(other)[source]

Return the minimal bounding box that contains both this bb and the other bb

right
top
wrap_vect(v)[source]

Returns a copy of v wrapped to the bounding box. That is, BB(0,0,10,10).wrap_vect((5,5)) == Vec2d(10,10)