Esempio n. 1
0
    def load(self):
        bodyDef = box2d.b2BodyDef()

        if self.shape.type == WorldConfig.BOX:
            bodyDef.position = self.shape.center[0], self.shape.center[1]
            body = WorldConfig.world.CreateBody(bodyDef)
            
            shapeDef = box2d.b2PolygonDef()
            shapeDef.SetAsBox(self.shape.width / 2, self.shape.height / 2)            
        elif self.shape.type == WorldConfig.POLYGON:
            body = WorldConfig.world.CreateBody(bodyDef)
            
            shapeDef = box2d.b2PolygonDef()
            shapeDef.setVertices(self.shape.points)
        elif self.shape.type == WorldConfig.CIRCLE:
            bodyDef.position = self.shape.x, self.shape.y
            body = WorldConfig.world.CreateBody(bodyDef)
            
            shapeDef = box2d.b2CircleDef()
            shapeDef.radius = self.shape.radius
        else:
            raise 'unknown shape'
            return 
                         
#        shapeDef.density = 1
#        shapeDef.friction = 0.1
#        shapeDef.restitution = 1.0
        shapeDef.filter.categoryBits = Wall.catBits
#        shapeDef.filter.maskBits = Wall.maskBits
        body.CreateShape(shapeDef)
        body.SetMassFromShapes()
        body.userData = self
        self.body = body
    def LaunchBomb(self, position, velocity):
        """
        A bomb is a simple circle which has the specified position and velocity.
        position and velocity must be b2Vec2's.
        """
        if self.bomb:
            self.world.DestroyBody(self.bomb)
            self.bomb = None

        bd = box2d.b2BodyDef()
        bd.allowSleep = True
        bd.position = position
        bd.isBullet = True
        self.bomb = self.world.CreateBody(bd)
        self.bomb.SetLinearVelocity(velocity)

        sd = box2d.b2CircleDef()
        sd.radius = 0.3
        sd.density = 20.0
        sd.restitution = 0.1

        minV = position - (0.3,0.3)
        maxV = position + (0.3,0.3)

        aabb = box2d.b2AABB()
        aabb.lowerBound = minV
        aabb.upperBound = maxV

        if self.world.InRange(aabb):
            self.bomb.CreateShape(sd)
            self.bomb.SetMassFromShapes()
Esempio n. 3
0
 def load(self, angle, radius, length):
     _x, _y=length*math.cos(angle),length*math.sin(angle)
     position= self.parent.body.position.x+_x, self.parent.body.position.y+_y
     bd=box2d.b2BodyDef()
     bd.fixedRotation=False
     bd.position=position
     
     sd=box2d.b2CircleDef()
     sd.radius=radius
     sd.density=1.0
     sd.filter.categoryBits= PistonBall.catBits
   
     self.body=WorldConfig.world.CreateBody(bd)
     self.body.CreateShape(sd)
     self.body.SetMassFromShapes()
     self.body.userData=self
         
     pjd=box2d.b2PrismaticJointDef() 
     pjd.Initialize(self.parent.body, self.body, self.parent.body.position, (math.cos(angle), math.sin(angle)))
     pjd.motorSpeed = 30.0
     pjd.maxMotorForce = 1000.0
     pjd.enableMotor = True
     pjd.lowerTranslation = 0.0
     pjd.upperTranslation = 10.0
     pjd.enableLimit = True
     
     self.joint=WorldConfig.world.CreateJoint(pjd).getAsType()
Esempio n. 4
0
    def LaunchBomb(self, position, velocity):
        """
        A bomb is a simple circle which has the specified position and velocity.
        position and velocity must be b2Vec2's.
        """
        if self.bomb:
            self.world.DestroyBody(self.bomb)
            self.bomb = None

        bd = box2d.b2BodyDef()
        bd.allowSleep = True
        bd.position = position
        bd.isBullet = True
        self.bomb = self.world.CreateBody(bd)
        self.bomb.SetLinearVelocity(velocity)

        sd = box2d.b2CircleDef()
        sd.radius = 0.3
        sd.density = 20.0
        sd.restitution = 0.1

        minV = position - (0.3, 0.3)
        maxV = position + (0.3, 0.3)

        aabb = box2d.b2AABB()
        aabb.lowerBound = minV
        aabb.upperBound = maxV

        if self.world.InRange(aabb):
            self.bomb.CreateShape(sd)
            self.bomb.SetMassFromShapes()
Esempio n. 5
0
    def __init__(self, world, x0, y0, theta0):
        # constants
        self.radius = 0.5

        # coordinates for drawing
        self.theta = theta0
        self.x = x0
        self.y = y0
        
        # first define a body
        bodyDef = physics.b2BodyDef()
        bodyDef.position = (self.x, self.y)
        # create body in our world
        self.body = world.CreateBody(bodyDef)

        # then define the attached shape
        # (it's a circle)
        shapeDef = physics.b2CircleDef()
        shapeDef.radius = self.radius
        shapeDef.density = 3
        # create the shape
        self.shape = self.body.CreateShape(shapeDef)
        # attach a mass
        self.body.SetMassFromShapes()

        # fixtures
        self.shape.friction = 1.0
        self.shape.restitution = 0.1

        # initial angular velocity
        self.body.angularVelocity = -30.0
Esempio n. 6
0
 def __init__(self, world, x, y):
     bodyDef = b2.b2BodyDef()
     bodyDef.position = (x, y)
     self.body = world.CreateBody(bodyDef)
     shapeDef = b2.b2CircleDef()
     shapeDef.radius = 0.25
     shapeDef.isSensor = True
     self.body.CreateShape(shapeDef)
     self.body.userData = self
Esempio n. 7
0
	def __init__(self, world, x, y):
		bodyDef = b2.b2BodyDef()
		bodyDef.position = (x, y)
		self.body = world.CreateBody(bodyDef)
		shapeDef = b2.b2CircleDef()
		shapeDef.radius = 0.25
		shapeDef.isSensor = True
		self.body.CreateShape(shapeDef)
		self.body.userData = self
Esempio n. 8
0
 def __init__(self, world, radius, density=1.0, friction=0.3):
     self.world = world
     self._display_list = None
     
     sd = box2d.b2CircleDef()
     sd.radius = radius
     sd.density = density
     sd.friction = friction
     self.shape_def = sd
Esempio n. 9
0
 def getShapeDef(self):
     if self.shapeDef == None:
         self.shapeDef = box2d.b2CircleDef()
         self.shapeDef.radius = self.radius
         self.shapeDef.density = 1
         self.shapeDef.friction = 0.0
         self.shapeDef.restitution = 0.5
         self.shapeDef.filter.categoryBits = Bullet.catBits
                 
     return self.shapeDef  
Esempio n. 10
0
 def __init__(self, world, pos, target, color):
   self.body = world.addBody(pos, None)
   bodyCircleDef = box2d.b2CircleDef()
   bodyCircleDef.radius = 0.5
   bodyCircleDef.localPosition.Set(0.0, 0.0)
   bodyCircleDef.density = 1.0
   bodyCircleDef.restitution = 0.6
   bodyCircleDef.friction = 0.5
   self.body.CreateShape(bodyCircleDef)
   self.body.SetMassFromShapes()
   self.pid = prim.TwodPIDController(kp=1.0, kd=600.0, ki=5.0, kiDamp=0.9)
   self.target = target
   self.color = color
Esempio n. 11
0
    def create(self, level):
        super(Ball, self).create(level)

        shapeDef = b2d.b2CircleDef()

        shapeDef.density = self.density
        shapeDef.restitution = self.restitution
        shapeDef.radius = self.radius

        shape = self.body.CreateShape(shapeDef)

        if not self.static:
            self.body.SetMassFromShapes()
Esempio n. 12
0
 def create_phisycs_object(self, world, dynamic):
     bodyDef = box2d.b2BodyDef()
     bodyDef.position = (self.position[0] + self.radius / 2, self.position[1] + self.radius / 2)
     bodyDef.userdata = self
     body = world.CreateBody(bodyDef)
     shapeDef = box2d.b2CircleDef()
     shapeDef.radius = self.radius
     if dynamic:
         shapeDef.density = 1
     shapeDef.linearDamping = 0.0
     shapeDef.angularDamping = 0.0
     shapeDef.friction = 0.1
     shapeDef.restitution = 1
     body.CreateShape(shapeDef)
     body.SetMassFromShapes()
     return body
Esempio n. 13
0
    def shape(self):

        if self.shape_type == 'box':
            self.blockShapeDef = box2d.b2PolygonDef()
            self.blockShapeDef.friction =0.3
            self.blockShapeDef.SetAsBox(self.x, self.y)#, self.position ,0)
        if self.shape_type == 'circle':
            self.blockShapeDef = box2d.b2CircleDef()
            self.blockShapeDef.friction =0.3
            #self.blockShapeDef.localPosition.Set(*self.position)
            self.blockShapeDef.localPosition.Set(0,0)
            self.blockShapeDef.radius = self.x
        if self.shape_type == 'triangle':
            self.blockShapeDef = box2d.b2PolygonDef()
            self.blockShapeDef.friction =0.3
            self.blockShapeDef.setVertices( [ (-self.x, 0.0), (self.x, 0.0), (0.0, self.y*2) ])
Esempio n. 14
0
  def __init__(self, env, sim, pos, color=hurrr.colors.LCARS.ORANGE, radius=0.5, density=1.0, restitution=0.6, friction=0.5, maxForce=10, maxTorque=10, sensors=None):
    super(PointBot, self).__init__(env, sim, maxForce, maxTorque, sensors)
    self.color = color
    self.radius = radius

    self.body = self.sim.addBody(pos, self)
    bodyCircleDef = box2d.b2CircleDef()
    bodyCircleDef.radius = self.radius
    bodyCircleDef.localPosition.Set(0.0, 0.0)
    bodyCircleDef.density = density
    bodyCircleDef.restitution = restitution
    bodyCircleDef.friction = friction
    self.body.CreateShape(bodyCircleDef)
    self.body.SetMassFromShapes()

    self.sensors = sensors or {}
    self.behavior = self.genBehavior()
Esempio n. 15
0
    def _initPhysics(self,world,pos):
        bodyDef=Box2D.b2BodyDef()
        pos=world.s2wPos(pos)
        bodyDef.position=Box2D.b2Vec2(pos[0],pos[1])
        #bodyDef.fixedRotation=True

        body=world.world.CreateBody(bodyDef)

        shapeDef=Box2D.b2CircleDef()
        shapeDef.radius=self.radiusW
        shapeDef.density=1
        shapeDef.friction=0.1
        shapeDef.restitution=0.5

        body.CreateShape(shapeDef)
        body.SetMassFromShapes()

        self.body=body
Esempio n. 16
0
    def explode(self):
        self._exploding = 1

        tank = self.body.userData['shooter'].name
        

        for ring, radius in enumerate(conf.explosion_radii):
            cdef = box2d.b2CircleDef()
            cdef.radius = radius

            s = self.body.CreateShape(cdef)
            s.userData = {}
            s.userData['ring'] = ring
            s.userData['bullet'] = self
            s.userData['hits'] = {0:[], 1:[], 2:[]}

        e = self.wld.v.addexplosion(self.body.position)
        self.e = e
Esempio n. 17
0
    def explode(self):
        self._exploding = 1

        #robot = self.body.userData['shooter'].name
        #print robot,'bullet explode at', self.body.position

        for ring, radius in enumerate(conf.explosion_radii):
            cdef = box2d.b2CircleDef()
            cdef.radius = radius

            s = self.body.CreateShape(cdef)
            s.userData = {}
            s.userData['ring'] = ring
            s.userData['bullet'] = self
            s.userData['hits'] = {0: [], 1: [], 2: []}

        e = self.wld.v.addexplosion(self.body.position)
        self.e = e
Esempio n. 18
0
    def shot(self):
#        self.forearm1.ApplyImpulse((80,0), self.forearm1.position)
        self.jarm1.SetMotorSpeed(100)
        angle= self.forearm1.GetAngle()-0.5*box2d.b2_pi    
        bd=box2d.b2BodyDef()
#        bd.position=self.forearm1.position.x+ 2*math.cos(angle), self.body.position.y+ 2*math.sin(angle)
        x, y =self.forearm1.shapeList[0].asPolygon().getCoreVertices_tuple()[0]
        bd.position= self.forearm1.GetWorldPoint(box2d.b2Vec2(x, y))
        
        sd=box2d.b2CircleDef()
        sd.radius=1
        sd.density=0.5
        sd.filter.categoryBits = Player.catBits        
        body=WorldConfig.world.CreateBody(bd)
        body.CreateShape(sd)
        body.SetMassFromShapes()

        body.ApplyImpulse( (500*math.cos(angle), 500*math.sin(angle) ), body.position)
Esempio n. 19
0
 def load(self, angle, num, length):
     bd=box2d.b2BodyDef()
     bd.fixedRotation=True
     pos=self.shape.center[0], self.shape.center[1]
     bd.position=pos
     
     sd=box2d.b2CircleDef()
     sd.radius=self.shape.width/2.0
     sd.density=1.0
   
     self.body=WorldConfig.world.CreateBody(bd)
     self.body.CreateShape(sd)
     self.body.userData=self
     
     for i in range(0, num):
         pb=PistonBall(self, angle=angle, length=length)
         self.legs.append(pb)
         angle+=2*box2d.b2_pi/num
Esempio n. 20
0
	def __init__(self, world, number, x, y):
		self.kill = False
		self.number = number
		if number > 8:
			self.color = self.colors[number - 8]
			self.stripe = True
		else:
			self.color = self.colors[number]
			self.stripe = False
		bodyDef = b2.b2BodyDef()
		bodyDef.position = (x, y)
		bodyDef.linearDamping = 0.9
		self.body = world.CreateBody(bodyDef)
		shapeDef = b2.b2CircleDef()
		shapeDef.radius = 0.3
		shapeDef.density = 1.7
		shapeDef.friction = 0.03
		shapeDef.restitution = 0.95
		self.body.CreateShape(shapeDef)
		self.body.SetMassFromShapes()
		self.body.userData = self
Esempio n. 21
0
 def __init__(self, world, number, x, y):
     self.kill = False
     self.number = number
     if number > 8:
         self.color = self.colors[number - 8]
         self.stripe = True
     else:
         self.color = self.colors[number]
         self.stripe = False
     bodyDef = b2.b2BodyDef()
     bodyDef.position = (x, y)
     bodyDef.linearDamping = 0.9
     self.body = world.CreateBody(bodyDef)
     shapeDef = b2.b2CircleDef()
     shapeDef.radius = 0.3
     shapeDef.density = 1.7
     shapeDef.friction = 0.03
     shapeDef.restitution = 0.95
     self.body.CreateShape(shapeDef)
     self.body.SetMassFromShapes()
     self.body.userData = self
Esempio n. 22
0
    def addPrismatic(self):
        sd1=box2d.b2CircleDef()
        sd1.radius = 2
        sd1.density = 2.0


        bd1=box2d.b2BodyDef()
        ppos= self.body.GetWorldCenter()
        
        bd1.position = (ppos.x+6, ppos.y)
        body_punch = WorldConfig.world.CreateBody(bd1)
        body_punch.CreateShape(sd1)
        body_punch.SetMassFromShapes()
        
        jointDef = box2d.b2PrismaticJointDef()
        jointDef.Initialize(self.body, body_punch,playerPos, (1.0,0.0))
        jointDef.lowerTranslation = 0.0
        jointDef.upperTranslation = 10
        jointDef.enableLimit      = True
        jointDef.motorSpeed       = 100.0
        jointDef.enableMotor      = True        
        WorldConfig.world.CreateJoint(jointDef).getAsType() 
        self.bodies.append(body_punch)
Esempio n. 23
0
    def __init__(self, world, x0, y0, theta0):
        # constantes
        self.radius = 4

        # coordonnees
        self.theta = theta0
        self.x = x0
        self.y = y0

        bodyDef = physics.b2BodyDef()
        bodyDef.position = (self.x, self.y)
        self.body = world.CreateBody(bodyDef)

        shapeDef = physics.b2CircleDef()
        shapeDef.radius = self.radius
        shapeDef.density = 3
        self.shape = self.body.CreateShape(shapeDef)
        self.body.SetMassFromShapes()

        self.shape.friction = 0.5
        self.shape.restitution = 0.7

        self.body.angularVelocity = -30.0
Esempio n. 24
0
    def json_load(self, path, additional_vars = {}):
        import cjson

        self.world.GetGroundBody().userData = {"saveid" : 0}

        f = open(path, 'r')
        worldmodel = cjson.decode(f.read())
        f.close()
        #clean world
        for joint in self.world.GetJointList():
            self.world.DestroyJoint(joint)
        for body in self.world.GetBodyList():
            if body != self.world.GetGroundBody():
                self.world.DestroyBody(body)

        #load bodys
        for body in worldmodel['bodylist']:
            bodyDef = box2d.b2BodyDef()
            bodyDef.position = body['position']
            bodyDef.userData = body['userData']
            bodyDef.angle = body['angle']
            newBody = self.world.CreateBody(bodyDef)
            #_logger.debug(newBody)
            newBody.angularVelocity = body['angularVelocity']
            newBody.linearVelocity = body['linearVelocity']
            if body.has_key('shapes'):
                for shape in body['shapes']:
                    if shape['type'] == 'polygon':
                        polyDef = box2d.b2PolygonDef()
                        polyDef.setVertices(shape['vertices'])
                        polyDef.density = shape['density']
                        polyDef.restitution = shape['restitution']
                        polyDef.friction = shape['friction']
                        newBody.CreateShape(polyDef)
                    if shape['type'] == 'circle':
                        circleDef = box2d.b2CircleDef()
                        circleDef.radius = shape['radius']
                        circleDef.density = shape['density']
                        circleDef.restitution = shape['restitution']
                        circleDef.friction = shape['friction']
                        circleDef.localPosition  = shape['localPosition']
                        newBody.CreateShape(circleDef)
                newBody.SetMassFromShapes()

        for joint in worldmodel['jointlist']:
            if joint['type'] == 'distance':
                jointDef = box2d.b2DistanceJointDef()
                body1 = self.getBodyWithSaveId(joint['body1'])
                anch1 = joint['anchor1']
                body2 = self.getBodyWithSaveId(joint['body2'])
                anch2 = joint['anchor2']
                jointDef.collideConnected = joint['collideConnected']
                jointDef.Initialize(body1,body2,anch1,anch2)
                jointDef.SetUserData(joint['userData'])
                self.world.CreateJoint(jointDef)
            if joint['type'] == 'revolute':
                jointDef = box2d.b2RevoluteJointDef()
                body1 = self.getBodyWithSaveId(joint['body1'])
                body2 = self.getBodyWithSaveId(joint['body2'])
                anchor = joint['anchor']
                jointDef.Initialize(body1,body2,anchor)
                jointDef.SetUserData(joint['userData'])
                jointDef.enableMotor = joint['enableMotor']
                jointDef.motorSpeed = joint['motorSpeed']
                jointDef.maxMotorTorque = joint['maxMotorTorque']
                self.world.CreateJoint(jointDef)

        for (k,v) in worldmodel['additional_vars'].items():
            additional_vars[k] = v

        for body in self.world.GetBodyList():
            del body.userData['saveid'] #remove temporary data
Esempio n. 25
0
    def __init__(self):
        global count
        # BodyDefs
        self.LFootDef=box2d.b2BodyDef()
        self.RFootDef=box2d.b2BodyDef()
        self.LCalfDef=box2d.b2BodyDef()
        self.RCalfDef=box2d.b2BodyDef()
        self.LThighDef=box2d.b2BodyDef()
        self.RThighDef=box2d.b2BodyDef()
        
        self.PelvisDef=box2d.b2BodyDef()
        self.StomachDef=box2d.b2BodyDef()
        self.ChestDef=box2d.b2BodyDef()
        self.NeckDef=box2d.b2BodyDef()
        self.HeadDef=box2d.b2BodyDef()
        
        self.LUpperArmDef=box2d.b2BodyDef()
        self.RUpperArmDef=box2d.b2BodyDef()
        self.LForearmDef=box2d.b2BodyDef()
        self.RForearmDef=box2d.b2BodyDef()
        self.LHandDef=box2d.b2BodyDef()
        self.RHandDef=box2d.b2BodyDef()
       
        # Polygons
        self.LFootPoly=box2d.b2PolygonDef()
        self.RFootPoly=box2d.b2PolygonDef()
        self.LCalfPoly=box2d.b2PolygonDef()
        self.RCalfPoly=box2d.b2PolygonDef()
        self.LThighPoly=box2d.b2PolygonDef()
        self.RThighPoly=box2d.b2PolygonDef()
        self.LFootPoly.friction = 0.7
        self.RFootPoly.friction = 0.7
       
        self.PelvisPoly=box2d.b2PolygonDef()
        self.StomachPoly=box2d.b2PolygonDef()
        self.ChestPoly=box2d.b2PolygonDef()
        self.NeckPoly=box2d.b2PolygonDef()
       
        self.LUpperArmPoly=box2d.b2PolygonDef()
        self.RUpperArmPoly=box2d.b2PolygonDef()
        self.LForearmPoly=box2d.b2PolygonDef()
        self.RForearmPoly=box2d.b2PolygonDef()
        self.LHandPoly=box2d.b2PolygonDef()
        self.RHandPoly=box2d.b2PolygonDef()
        
        # Circles
        self.HeadCirc=box2d.b2CircleDef()
        
        # Revolute Joints
        self.LAnkleDef=box2d.b2RevoluteJointDef()
        self.RAnkleDef=box2d.b2RevoluteJointDef()
        self.LKneeDef=box2d.b2RevoluteJointDef()
        self.RKneeDef=box2d.b2RevoluteJointDef()
        self.LHipDef=box2d.b2RevoluteJointDef()
        self.RHipDef=box2d.b2RevoluteJointDef()
        
        self.LowerAbsDef=box2d.b2RevoluteJointDef()
        self.UpperAbsDef=box2d.b2RevoluteJointDef()
        self.LowerNeckDef=box2d.b2RevoluteJointDef()
        self.UpperNeckDef=box2d.b2RevoluteJointDef()
       
        self.LShoulderDef=box2d.b2RevoluteJointDef()
        self.RShoulderDef=box2d.b2RevoluteJointDef()
        self.LElbowDef=box2d.b2RevoluteJointDef()
        self.RElbowDef=box2d.b2RevoluteJointDef()
        self.LWristDef=box2d.b2RevoluteJointDef()
        self.RWristDef=box2d.b2RevoluteJointDef()
        
        self.iter_polys = ( self.LFootPoly, self.RFootPoly, self.LCalfPoly, self.RCalfPoly, self.LThighPoly, self.RThighPoly,
                self.PelvisPoly, self.StomachPoly, self.ChestPoly, self.NeckPoly,
                self.LUpperArmPoly, self.RUpperArmPoly, self.LForearmPoly, self.RForearmPoly, self.LHandPoly, self.RHandPoly ,
                self.HeadCirc )
        self.iter_defs = ( self.LFootDef, self.RFootDef, self.LCalfDef, self.RCalfDef, self.LThighDef, self.RThighDef,
                self.PelvisDef, self.StomachDef, self.ChestDef, self.NeckDef, self.HeadDef,
                self.LUpperArmDef, self.RUpperArmDef, self.LForearmDef, self.RForearmDef, self.LHandDef, self.RHandDef )
        self.iter_joints=( self.LAnkleDef, self.RAnkleDef, self.LKneeDef, self.RKneeDef, self.LHipDef, self.RHipDef,
                self.LowerAbsDef, self.UpperAbsDef, self.LowerNeckDef, self.UpperNeckDef,
                self.LShoulderDef, self.RShoulderDef, self.LElbowDef, self.RElbowDef, self.LWristDef, self.RWristDef )

        self.SetMotorTorque(2.0)
        self.SetMotorSpeed(0.0)
        self.SetDensity(1.0)
        self.SetRestitution(0.0)
        self.SetLinearDamping(0.0)
        self.SetAngularDamping(0.005)
        count -= 1
        self.SetGroupIndex(count)
        self.EnableMotor()
        self.EnableLimit()

        self.DefaultVertices()
        self.DefaultPositions()
        self.DefaultJoints()

        self.LFootPoly.friction = self.RFootPoly.friction = 1.85
Esempio n. 26
0
 def shape_def(self):
     if self._shape_def is None:
         self._shape_def = box2d.b2CircleDef()
         self.apply_properties_to_def(self.shape_def)
     return self._shape_def
Esempio n. 27
0
body = world.CreateBody(bodyDef)
shapeDef = box2d.b2PolygonDef()
shapeDef.SetAsBox(6, 0.8)
shapeDef.density = 0.1
shapeDef.friction = 0
shapeDef.restitution = 1 
shapeDef.userData = 'bat'
body.CreateShape(shapeDef)
body.SetMassFromShapes()

ballbodydef = box2d.b2BodyDef()
ballbodydef.position = (0,-20)
ballbodydef.isBullet = True
ballbodydef.angularDamping = 1000000
ball = world.CreateBody(ballbodydef)
ballshapedef = box2d.b2CircleDef()
ballshapedef.density = 0.1 
ballshapedef.friction = 0
ballshapedef.restitution = 0.8 
ballshapedef.radius = 2
ballshapedef.userData = 'ball'
ball.CreateShape(ballshapedef)
ball.SetMassFromShapes()

groundBodyDef = box2d.b2BodyDef()
groundBodyDef.position = (0, 0)
groundBody = world.CreateBody(groundBodyDef)
groundShapeDef = box2d.b2PolygonDef()
groundShapeDef.friction =0.3
groundShapeDef.SetAsBox(80, 1, (0,-29),0)
groundShapeDef.userData = "wall"
Esempio n. 28
0
screen = pygame.display.set_mode(SCREEN_SIZE)
my_font = pygame.font.Font(None, 14)

# physical worls generation
world_BB = box2d.b2AABB()
world_BB.lowerBound.Set(p2b_units(-100), p2b_units(-WORLD_SIZE[1]))
world_BB.upperBound.Set(p2b_units(WORLD_SIZE[0]),  p2b_units(100))
world = box2d.b2World(world_BB, box2d.b2Vec2(0, 0), True)

# player physics generation
player_body_def = box2d.b2BodyDef()
player_body_def.position = player_pos_b
player_body = world.CreateBody(player_body_def)
del player_body_def

player_shape_def = box2d.b2CircleDef()
player_shape_def.density = 5.0
player_shape_def.friction = 0.3
player_shape_def.radius = p2b_units(PLAYER_RADIUS)
player_shape_def.restitution = RESTITUTION

player_body.CreateShape(player_shape_def)
player_body.SetMassFromShapes()

# level physics generation
particle_bodies = []
particle_gravs  = []

for pos,r,c in PARTICLE_INFO:
    temp_def = box2d.b2BodyDef()
    temp_def.position = p2b_coor(pos)
Esempio n. 29
0
    def json_load(self, path, serialized=False):
        import json

        self.world.GetGroundBody().userData = {"saveid": 0}

        f = open(path, 'r')
        worldmodel = json.loads(f.read())
        f.close()
        # clean world
        for joint in self.world.GetJointList():
            self.world.DestroyJoint(joint)
        for body in self.world.GetBodyList():
            if body != self.world.GetGroundBody():
                self.world.DestroyBody(body)

        # load bodies
        for body in worldmodel['bodylist']:
            bodyDef = box2d.b2BodyDef()
            bodyDef.position = body['position']
            bodyDef.userData = body['userData']
            bodyDef.angle = body['angle']
            newBody = self.world.CreateBody(bodyDef)
            #_logger.debug(newBody)
            newBody.angularVelocity = body['angularVelocity']
            newBody.linearVelocity = body['linearVelocity']
            if 'shapes' in body:
                for shape in body['shapes']:
                    if shape['type'] == 'polygon':
                        polyDef = box2d.b2PolygonDef()
                        polyDef.setVertices(shape['vertices'])
                        polyDef.density = shape['density']
                        polyDef.restitution = shape['restitution']
                        polyDef.friction = shape['friction']
                        newBody.CreateShape(polyDef)
                    if shape['type'] == 'circle':
                        circleDef = box2d.b2CircleDef()
                        circleDef.radius = shape['radius']
                        circleDef.density = shape['density']
                        circleDef.restitution = shape['restitution']
                        circleDef.friction = shape['friction']
                        circleDef.localPosition = shape['localPosition']
                        newBody.CreateShape(circleDef)
                newBody.SetMassFromShapes()

        for joint in worldmodel['jointlist']:
            if joint['type'] == 'distance':
                jointDef = box2d.b2DistanceJointDef()
                body1 = self.getBodyWithSaveId(joint['body1'])
                anch1 = joint['anchor1']
                body2 = self.getBodyWithSaveId(joint['body2'])
                anch2 = joint['anchor2']
                jointDef.collideConnected = joint['collideConnected']
                jointDef.Initialize(body1, body2, anch1, anch2)
                jointDef.SetUserData(joint['userData'])
                self.world.CreateJoint(jointDef)
            if joint['type'] == 'revolute':
                jointDef = box2d.b2RevoluteJointDef()
                body1 = self.getBodyWithSaveId(joint['body1'])
                body2 = self.getBodyWithSaveId(joint['body2'])
                anchor = joint['anchor']
                jointDef.Initialize(body1, body2, anchor)
                jointDef.SetUserData(joint['userData'])
                jointDef.enableMotor = joint['enableMotor']
                jointDef.motorSpeed = joint['motorSpeed']
                jointDef.maxMotorTorque = joint['maxMotorTorque']
                self.world.CreateJoint(jointDef)

        self.additional_vars = {}
        addvars = {}
        for (k, v) in worldmodel['additional_vars'].items():
            addvars[k] = v

        if serialized and 'trackinfo' in addvars:
            trackinfo = addvars['trackinfo']
            for key, info in trackinfo.iteritems():
                if not info[3]:
                    addvars['trackinfo'][key][0] = \
                        self.getBodyWithSaveId(info[0])
                    addvars['trackinfo'][key][1] = \
                        self.getBodyWithSaveId(info[1])
                else:
                    addvars['trackinfo'][key][0] = None
                    addvars['trackinfo'][key][1] = None

        self.additional_vars = addvars

        for body in self.world.GetBodyList():
            del body.userData['saveid']  # remove temporary data
Esempio n. 30
0
def main():
    # Initialize pygame
    screen = pygame.display.set_mode((width,height))

    caption= "Python Box2D Testbed Demos"
    pygame.display.set_caption(caption)

    # Initialize the GUI
    theme = gui.Theme("default")
    app = gui.Desktop(theme=theme)

    app.connect(gui.QUIT,app.quit,None)

    main = gui.Container(width=width, height=height)

    # Label at the top left
    main.add(gui.Label("Box2D Testbed Demos", cls="h1"), 20, 20)

    # The dimensions of the list of the demos
    list_size= (width / 2, height / 2)
    list_pos = (width/2 - list_size[0]/2, height/2 - list_size[1]/2)

    # Create the actual widget
    demolist = gui.List(width=list_size[0], height=list_size[1])
    main.add(demolist, list_pos[0], list_pos[1])

    # Add all the demos found in the directory to the list
    add_demos(demolist)

    
    buttonw = (list_size[0]/2-20)        # width of the buttons
    bottom = list_pos[1]+list_size[1]+20 # the y-location of the bottom of the list

    # Create a Run button, calling run_demo on click
    b = gui.Button("Run", width=buttonw)
    main.add(b, list_pos[0], bottom)
    b.connect(gui.CLICK, run_demo, demolist)

    # Create a Quit button
    b = gui.Button("Quit", width=buttonw)
    main.add(b, list_pos[0]+buttonw+30, bottom)
    b.connect(gui.CLICK, lambda x:pygame.event.post(pygame.event.Event(pygame.QUIT)), None)

    # box2d initialization
    z=10 #scale (10 pixels/physics unit)

    # Since we're taking the debug draw implementation from the testbed, it requires a bit
    # of ugliness to set it up properly.
    renderer = fwDebugDraw()
    renderer.surface = screen
    renderer.viewZoom=z
    renderer.viewCenter=box2d.b2Vec2(0,0)
    renderer.width, renderer.height = width, height
    renderer.viewOffset = renderer.viewCenter - box2d.b2Vec2(width, height)/2
    renderer.SetFlags(box2d.b2DebugDraw.e_shapeBit) # we only want shapes to be drawn
    renderer.DrawSolidPolygon = lambda *args: 0 # make it not draw the polygons!
    renderer.DrawPolygon = lambda *args: 0      #

    # Create the world
    worldAABB=box2d.b2AABB()
    worldAABB.lowerBound = (-100.0, -100.0)
    worldAABB.upperBound = ( 100.0, 100.0)
    gravity = (0.0, -10.0)

    world = box2d.b2World(worldAABB, gravity, True)
    world.SetDebugDraw(renderer)

    # Create the ground
    bd = box2d.b2BodyDef()
    bd.position = (0.0, 0.0)
    ground = world.CreateBody(bd)
    
    # The borders of the screen
    sd = box2d.b2PolygonDef()
    sd.SetAsBox(1, height/z, (-width/(2*z)-1, 0), 0)
    ground.CreateShape(sd)
    sd.SetAsBox(1, height/z, (width/(2*z)+1, 0), 0)
    ground.CreateShape(sd)
    sd.SetAsBox(width/z, 1, (0,-height/(2*z)-1), 0)
    ground.CreateShape(sd)
    sd.SetAsBox(width/z, 1, (0,height/(2*z)+1), 0)
    ground.CreateShape(sd)

    # The shape for the file list
    sd.SetAsBox(list_size[0]/(2*z), list_size[1]/(2*z))
    ground.CreateShape(sd)

    # Create a few balls to bounce around the screen
    for i in range(10):
        bd = box2d.b2BodyDef()
        bd.allowSleep = True
        bd.position = (box2d.b2Random(-width/(2*z), width/(2*z)), box2d.b2Random(-height/(2*z), height/(2*z)))
        bd.isBullet = True
        bomb = world.CreateBody(bd)
        bomb.SetLinearVelocity(-5.0 * bd.position)

        sd = box2d.b2CircleDef()
        sd.radius = 1
        sd.density = 1.0
        sd.restitution = 0.7
        bomb.CreateShape(sd)
        
        bomb.SetMassFromShapes()

    app.init(main)
    main_loop(world, screen, demolist, app)
Esempio n. 31
0
#!/usr/bin/python2.6
Esempio n. 32
0
#!/usr/bin/python2.6