Submodules
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]
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.
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).
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).
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.
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 : |
|
---|
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 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 : |
|
---|
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 : |
|
---|---|
Return : | True if key was not previously added, False otherwise |
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.
A list of the bodies added to this space
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.
Number of frames that contact information should persist.
Defaults to 3. There is probably never a reason to change this value.
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.
A list of the constraints added to this space
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.
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.
Default gravity to supply when integrating rigid body motions.
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.
Number of iterations to use in the impulse solver to solve contacts.
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 : |
|
---|---|
Return : | [dict(shape=`Shape`, distance = distance, point = Vec2d)] |
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 : |
|
---|---|
Return : | dict(shape=`Shape`, distance = distance, point = Vec2d) |
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 : |
|
---|
Query space at point and return the first shape found matching the given layers and group. Returns None if no shape was found.
Parameters : |
|
---|
Update the collision detection data for a specific shape in the space.
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 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 a collision handler for a given collision type pair.
Parameters : |
|
---|
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. |
---|
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.
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 : |
|
---|
Query a space for any shapes overlapping the given shape
Returns a list of shapes.
A list of all the shapes added to this space (both static and non-static)
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.
A convenience static body already added to the space
Bases: object
A rigid body
Create a new Body
To create a static body, pass in None for mass and moment.
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.
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 : |
|
---|
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 : |
|
---|
Get the constraints this body is attached to.
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!
Returns true if the body has not been added to a space.
Returns true if the body is sleeping.
Returns true if the body is a static body
Get the kinetic energy of a body.
Convert body local coordinates to world space coordinates
Parameters : |
|
---|
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.
Get the shapes attached to this body.
Force a body to fall asleep immediately along with other bodies in a group.
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.
Default rigid body velocity integration function.
Updates the velocity of the body using Euler integration.
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.
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.
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().
The body this shape is attached to. Can be set to None to indicate that this shape doesnt belong to a body.
User defined collision type for the shape. See add_collisionpair_func function for more information on when to use this property
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 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 |
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
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
Check if the line segment from start to end intersects the shape.
Return either SegmentQueryInfo object or None
A boolean value if this shape is a sensor or not. Sensors only call collision callbacks, and never generate real collisions.
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.
Bases: pymunk.Shape
A circle shape defined by a radius
This is the fastest and simplest collision shape
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.
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().
The body this shape is attached to. Can be set to None to indicate that this shape doesnt belong to a body.
Update and returns the bouding box of this shape
User defined collision type for the shape. See add_collisionpair_func function for more information on when to use this property
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 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 |
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
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. (body space coordinates)
Check if the given point lies within the shape.
The Radius of the circle
Check if the line segment from start to end intersects the shape.
Return either SegmentQueryInfo object or None
A boolean value if this shape is a sensor or not. Sensors only call collision callbacks, and never generate real collisions.
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 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 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, 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.
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.
Create a polygon
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().
The body this shape is attached to. Can be set to None to indicate that this shape doesnt belong to a body.
Update and returns the bouding box of this shape
User defined collision type for the shape. See add_collisionpair_func function for more information on when to use this property
Convenience function to create a box centered around the body position.
The size is given as as (w,h) tuple.
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 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 the vertices in world coordinates for the polygon
Returns: | [Vec2d] in world coords |
---|
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
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
Check if the given point lies within the shape.
The radius of the poly shape. Extends the poly in all directions with the given radius
Check if the line segment from start to end intersects the shape.
Return either SegmentQueryInfo object or None
A boolean value if this shape is a sensor or not. Sensors only call collision callbacks, and never generate real collisions.
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 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 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, 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.
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.
Create a Segment
Parameters : |
|
---|
The first of the two endpoints for this segment
The second of the two endpoints for this segment
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().
The body this shape is attached to. Can be set to None to indicate that this shape doesnt belong to a body.
Update and returns the bouding box of this shape
User defined collision type for the shape. See add_collisionpair_func function for more information on when to use this property
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 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 |
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
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
Check if the given point lies within the shape.
The radius/thickness of the segment
Check if the line segment from start to end intersects the shape.
Return either SegmentQueryInfo object or None
A boolean value if this shape is a sensor or not. Sensors only call collision callbacks, and never generate real collisions.
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.
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!
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!
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, 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.
Calculate the moment of inertia for a circle
Calculate the moment of inertia for a polygon
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.
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.
You shouldn’t need to initialize SegmentQueryInfo objects on your own.
Return the hit point in world coordinates where the segment first intersected with the shape
Normal of hit surface
Shape that was hit
Distance along query segment, will always be in the range [0, 1]
Bases: object
Contact information
Initialize a Contact object from the Chipmunk equivalent struct
Note
You should never need to create an instance of this class directly.
Penetration distance
Contact normal
Contact position
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.
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.
Information on the contact points between the objects. Return [Contact]
Elasticity
Friction
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.
Get the shapes in the order that they were defined in the collision handler associated with this arbiter
Time stamp of the arbiter. (from the space)
Used for surface_v calculations, implementation may change
Returns the impulse that was applied this step to resolve the collision.
This property should only be called from a post-solve, post-step
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
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
Bases: object
Simple bounding box class. Stored as left, bottom, right, top values.
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)
Return the minimal bounding box that contans both this bounding box and the vector v