Altering physics behaviour in Python

From Digital Spaces

Jump to: navigation, search

This example does the same thing as the previous example, Setting physics collision properties in Python, but does it in a way that can be altered at run time.

if 'dynamicCollisions' not in locals().keys():
	class PhysicsCollisionListener:
		def __init__(self, shapeNames, otherShapeNames ):
			if isinstance( shapeNames, str ):
				self.shapeNames = ( shapeNames, )
			else:
				self.shapeNames = shapeNames
 
			if isinstance( otherShapeNames, str ):
				self.otherShapeNames = ( otherShapeNames, )
			else:
				self.otherShapeNames = otherShapeNames
				
			for physics in dss_core.DIPhysics.GetFactoriesWithInterface():
				physics.AddShapeCollisionListener( self.OnCollision )
				
		def OnCollision(self, collision):
			shape1 = collision.GetShape()
			shape2 = collision.GetOtherShape()
			
			if ( shape1.GetName() in self.shapeNames and shape2.GetName() in self.otherShapeNames ) or
				( shape2.GetName() in self.shapeNames and shape1.GetName() in self.otherShapeNames ) )
				material = collision.GetMaterial()
				materialBase = dss_core.DIPhysicsBase.cast(material)
				materialBase.SetFloat( "staticFriction", 1.5 )
				materialBase.SetFloat( "kineticFriction", 0.5 )
				materialBase.SetBool( "pyramidFriction", True )
	
	dynamicCollisions = PhysicsCollisionListener( 
		( "vehicle_wheel1_shape", "vehicle_wheel2_shape", "vehicle_wheel3_shape", "vehicle_wheel4_shape", ),
		 "terrain_shape" )
 

The use of a callback function, OnCollision, allows the developer to insert logic that is processed when the collision occurs, rather then previously (using SetContactBetweenShapes) or retroactively (GetCollisionsLastHeartbeat). The only logic this example does is checks if the shapes involved in the collision are the specified ones, but much more could be done.

To see the properties that can be set here, see the API documentation for DIPhysicsMaterial.

Personal tools