def _poly(self, pos, vertices, dynamic=True, density=1.0, restitution=0.16, friction=0.5): # add a centered poly at pos without correcting any settings # meaning, pos and vertices are in meters x, y = pos bodyDef = box2d.b2BodyDef() bodyDef.position = (x, y) userData = {'color': self.parent.get_color()} bodyDef.userData = userData # Create the Body if not dynamic: density = 0 else: bodyDef.type = box2d.b2_dynamicBody body = self.parent.world.CreateBody(bodyDef) self.parent.element_count += 1 # Add a shape to the Body polyDef = box2d.b2FixtureDef() polygonShape = box2d.b2PolygonShape() polygonShape.vertices = vertices polyDef.shape = polygonShape polyDef.density = density polyDef.restitution = restitution polyDef.friction = friction body.CreateFixture(polyDef) return 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()
def createBox(position, w=1.0, h=1.0, wdiv=1, hdiv=1, bDynamic=True, density=1, friction=0.3, damping=0, collisionGroup=None, restitution=None, bCollideNoOne=False, name="",angle=0,categoryBits=0x0001, maskBits=0x0009): global world bodyDef = Box2D.b2BodyDef() bodyDef.position = position if(abs(world.gravity[1]) > 1): bodyDef.linearDamping = damping bodyDef.angularDamping = 0 else: bodyDef.linearDamping = 70 bodyDef.angularDamping = 50 if bDynamic: bodyDef.type = Box2D.b2_dynamicBody else: bodyDef.type = Box2D.b2_staticBody body = world.CreateBody(bodyDef) body.userData = {"name":name} dw = w / float(wdiv) dh = h / float(hdiv) for i in range(hdiv): for j in range(wdiv): x = 2*j*dw + (1-wdiv)*dw y = 2*i*dh + (1-hdiv)*dh fixtureDef = createBoxFixture((x, y), width=dw, height=dh, bDynamic=bDynamic, density=density, friction=friction, collisionGroup=collisionGroup, restitution=restitution, angle=angle) if(bCollideNoOne): fixtureDef.filter.maskBits = 0x0000 fixture = body.CreateFixture(fixtureDef,categoryBits=categoryBits,maskBits=maskBits) return body
def randomize(self, N, x0, x1, rng): # randomize how hilly the terrain is. lower number = softer hills terrain_freq = 10 + 14 * rng.rand() # construct random terrain using frequency domain low-freq noise modulus = np.exp(-np.arange(N) / terrain_freq) * rng.randn(N) argument = rng.randn(N) freqspace = modulus * np.cos(argument) + 1j * modulus * np.sin( argument) z = np.fft.fft(freqspace).real zmin = np.min(z) zmax = np.max(z) self.z = (TERRAIN_Z_RANGE / (zmax - zmin)) * (z - zmin) self.x = np.linspace(x0, x1, N) # construct box2d world for lidar. self.world = Box2D.b2World() verts = zip(self.x, self.z) nverts = len(verts) for i in range(nverts - 1): p0, p1 = verts[i], verts[i + 1] edge = Box2D.b2EdgeShape(vertices=[p0, p1]) body = Box2D.b2BodyDef( type=Box2D.b2_staticBody, fixtures=Box2D.b2FixtureDef(shape=edge, friction=0), ) self.world.CreateBody(body)
def add_body( b2_world, # jsw, # loaded json b2World jsw_body ): # create body definition bodyDef = b2.b2BodyDef() # Done with minor issues # missing pybox2d inertiaScale setAttr(jsw, "allowSleep", bodyDef) setAttr(jsw_body, "angle", bodyDef) setAttr(jsw_body, "angularDamping", bodyDef) setAttr(jsw_body, "angularVelocity", bodyDef) setAttr(jsw_body, "awake", bodyDef) setAttr(jsw_body, "bullet", bodyDef) setAttr(jsw_body, "fixedRotation", bodyDef) setAttr(jsw_body, "linearDamping", bodyDef) setB2Vec2Attr(jsw_body, "linearVelocity", bodyDef) setB2Vec2Attr(jsw_body, "position", bodyDef) setAttr(jsw_body, "gravityScale", bodyDef) # pybox2d non documented # setAttr(jsw_body, "massData-I", bodyDef, "inertiaScale") setAttr(jsw_body, "type", bodyDef) setAttr(jsw_body, "awake", bodyDef) # create body body_ref = b2_world.CreateBody(bodyDef) for fixture in jsw_body["fixture"]: add_fixture(body_ref, jsw, fixture)
def createCircle(position, r=0.3, bDynamic=True, bCollideNoOne=False, density=1, damping=0.05, restitution=0.1, friction=200, name="",categoryBits=0x0001,maskBits=0x0009): global world, fig, ax bodyDef = Box2D.b2BodyDef() bodyDef.position = position if bDynamic: bodyDef.type = Box2D.b2_dynamicBody else: bodyDef.type = Box2D.b2_staticBody if(abs(world.gravity[1]) > 1): bodyDef.linearDamping = damping bodyDef.angularDamping = damping else: bodyDef.linearDamping = 70 bodyDef.angularDamping = 30 body = world.CreateBody(bodyDef) shape = Box2D.b2CircleShape(radius=r) mask=maskBits if(bCollideNoOne): mask = 0x0000 fixture = body.CreateFixture(maskBits=mask, shape=shape, density=density, restitution=restitution, friction=friction,categoryBits=categoryBits) body.userData = {"name": name} return body
def createBox(position, w=1.0, h=1.0, wdiv = 1, hdiv = 1, dynamic=True, damping = 0, collisionGroup = None, bMatplotlib = True, restitution=None): global world, ax bodyDef = Box2D.b2BodyDef() bodyDef.position = position if(abs(world.gravity[1]) > 1): bodyDef.linearDamping = damping bodyDef.angularDamping = 0 else: bodyDef.linearDamping = 70 bodyDef.angularDamping = 50 if dynamic: bodyDef.type = Box2D.b2_dynamicBody else: bodyDef.type = Box2D.b2_staticBody body = world.CreateBody(bodyDef) dw = w / float(wdiv) dh = h / float(hdiv) for i in range(hdiv): for j in range(wdiv): x = 2*j*dw + (1-wdiv)*dw y = 2*i*dh + (1-hdiv)*dh fixtureDef = createBoxFixture(body, (x,y), width=dw, height=dh, collisionGroup = collisionGroup, restitution=restitution) fixture = body.CreateFixture(fixtureDef) if(bMatplotlib): createGlobalFigure() fixture.userData = drawBox2D(ax,body,fixture) return body
def createCircle(position, r=0.3, dynamic=True, bMatplotlib = True): global world, fig, ax bodyDef = Box2D.b2BodyDef() fixtureDef = Box2D.b2FixtureDef() if dynamic: bodyDef.type = Box2D.b2_dynamicBody fixtureDef.density = 1 else: bodyDef.type = Box2D.b2_staticBody fixtureDef.density = 0 bodyDef.position = position if(abs(world.gravity[1]) > 1): bodyDef.linearDamping = 0.1 bodyDef.angularDamping = 0.1 else: bodyDef.linearDamping = 70 bodyDef.angularDamping = 30 body = world.CreateBody(bodyDef) fixture = body.CreateFixture(shape=Box2D.b2CircleShape(radius=r), density=1.0, friction=0.3) if(bMatplotlib): createGlobalFigure() fixture.userData = drawCircle(ax,position,r) return body
def __init__(self, env, size, pos, world): # static rectangle shaped prop # pars: # size - array [width, height] # position - array [x, y], in world meters, of center self.env = env self.size = size self.pos = pos # initialize body bdef = Box2D.b2BodyDef() bdef.position = Box2D.b2Vec2(self.pos[0], self.pos[1]) bdef.angle = 0 bdef.fixedRotation = True self.body = world.CreateBody(bdef) # strange rect due to Box2D's way of representing objects self.rect = pygame.rect.Rect(self.pos[0] - self.size[0]/2, self.pos[1] - self.size[1]/2, self.size[0], self.size[1]) # initialize shape fixdef = Box2D.b2FixtureDef() fixdef.shape = Box2D.b2PolygonShape() fixdef.shape.SetAsBox(self.size[0]/2, self.size[1]/2) fixdef.restitution = 0.4 self.body.CreateFixture(fixdef)
def __init__(self,physics,bl,tr,tc = None): #Hardcode the dirt texture since right now all static things are dirt. I know I know. self.dead = False self.tc = tc if tc != None: self.InitPolygons(tc) self.visible = True else: self.visible = False self.physics = physics self.bodydef = box2d.b2BodyDef() midpoint = (tr - bl)*0.5*physics.scale_factor self.bodydef.position = tuple((bl*physics.scale_factor) + midpoint) self.shape = self.CreateShape(midpoint) if not self.static: self.shape.userData = self if self.filter_group != None: self.shape.filter.groupIndex = self.filter_group self.bodydef.isBullet = self.isBullet self.body = physics.world.CreateBody(self.bodydef) self.shape.density = self.mass self.shape.friction = 0.7 self.shapeI = self.body.CreateShape(self.shape) self.child_joint = None self.parent_joint = None self.PhysUpdate()
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 handle_enter(self, parameters): self.next_state = parameters['next_state'] self.next_state_parameters = parameters.setdefault('parameters', {}) self.next_state_parameters={'totalScore':parameters['totalScore'],'edit':parameters['edit']} self.delay = parameters.setdefault('delay', 2000) self.time_passed = 0 self.background = None self.shader = None self.screenFont = pygame.font.Font("data/font/fsex2p00_public.ttf", 70) text = u"Тоглоом дууслаа" self.message = self.screenFont.render(text, True, (255,255,255)) bodyDef = box2d.b2BodyDef() bodyDef.position = (8, -2) bodyDef.angle = -0.5 bodyDef.userData = self self.message_body = self.world.CreateBody(bodyDef) shapeDef = box2d.b2PolygonDef() shapeDef.density = 0.5 shapeDef.friction = 0.95 shapeDef.restitution = 0.5 shapeDef.SetAsBox(self.message.get_width()/2.0/self.pixels_per_unit, self.message.get_height()/2.0/self.pixels_per_unit) self.message_body.CreateShape(shapeDef) self.message_body.SetMassFromShapes() self.message_body.SetLinearVelocity = box2d.b2Vec2(100.0,0)
def __init__(self, xpos, ypos, dimensionX, dimensionY, isDynamic): # Creating the body definition self.bodyDef = Box2D.b2BodyDef() if isDynamic: self.bodyDef.type = Box2D.b2_dynamicBody else: self.bodyDef.type = Box2D.b2_staticBody # put object to "Sleep" to spare CPU self.bodyDef.awake = False self.bodyDef.position = (xpos, ypos) # platform body in world self.body = world.CreateBody(self.bodyDef) self.body.mass = 0.001 # platform box shape self.objectBox = Box2D.b2PolygonShape(box=(dimensionX / 2, dimensionY / 2)) # fixture definition if isDynamic: self.objectBoxFixture = Box2D.b2FixtureDef(shape=self.objectBox) else: self.objectBoxFixture = Box2D.b2FixtureDef(shape=self.objectBox, density=1, friction=0.3) self.body.CreateFixture(self.objectBoxFixture) # the boundaries # The boundaries ground = world.CreateBody(position=(400, 0)) ground.CreateEdgeChain([(-1200, -1200), (-1200, 1200), (2000, 2000), (2000, -1200), (-1200, -1200)]) world.CreateFrictionJoint(bodyA=ground, bodyB=self.body)
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
def __init__(self, physics, bl, tr, tc=None, angle=0): #Hardcode the dirt texture since right now all static things are dirt. I know I know. self.dead = False self.tc = tc self.bl = bl self.tr = tr if tc != None: self.InitPolygons(tc) self.visible = True else: self.visible = False self.physics = physics self.bodydef = box2d.b2BodyDef() #This is inefficient, but it doesn't want to grab properly otherwise. Shitty hack but whatever self.bodydef.allowSleep = False self.midpoint = (tr - bl) * 0.5 * physics.scale_factor self.bodydef.position = tuple((bl * physics.scale_factor) + self.midpoint) self.bodydef.angle = angle self.shape = self.CreateShape(self.midpoint) if not self.static: self.shape.userData = self if self.filter_group != None: self.shape.filter.groupIndex = self.filter_group self.bodydef.isBullet = self.isBullet self.body = physics.world.CreateBody(self.bodydef) self.shape.density = self.mass self.shape.friction = 0.7 self.shapeI = self.body.CreateShape(self.shape) self.child_joint = None self.parent_joint = None self.ExtraShapes() self.PhysUpdate()
def _rect(self, pos, width, height, angle=0, dynamic=True, density=1.0, restitution=0.16, friction=0.5): # Add a rect without correcting any settings # meaning, pos and vertices are in meters # angle is now in radians ((degrees * pi) / 180)) x, y = pos bodyDef = box2d.b2BodyDef() bodyDef.position = (x, y) userData = {'color': self.parent.get_color()} bodyDef.userData = userData # Create the Body if not dynamic: density = 0 else: bodyDef.type = box2d.b2_dynamicBody body = self.parent.world.CreateBody(bodyDef) self.parent.element_count += 1 # Add a shape to the Body boxDef = box2d.b2FixtureDef() polygonShape = box2d.b2PolygonShape() polygonShape.SetAsBox(width, height, (0, 0), angle) boxDef.shape = polygonShape boxDef.density = density boxDef.restitution = restitution boxDef.friction = friction body.CreateFixture(boxDef) return body
def add_body( b2_world, # jsw, # loaded json b2World jsw_body): # create body definition bodyDef = b2.b2BodyDef() # Done with minor issues # missing pybox2d inertiaScale setAttr(jsw, "allowSleep", bodyDef) setAttr(jsw_body, "angle", bodyDef) setAttr(jsw_body, "angularDamping", bodyDef) setAttr(jsw_body, "angularVelocity", bodyDef) setAttr(jsw_body, "awake", bodyDef) setAttr(jsw_body, "bullet", bodyDef) setAttr(jsw_body, "fixedRotation", bodyDef) setAttr(jsw_body, "linearDamping", bodyDef) setB2Vec2Attr(jsw_body, "linearVelocity", bodyDef) setB2Vec2Attr(jsw_body, "position", bodyDef) setAttr(jsw_body, "gravityScale", bodyDef) # pybox2d non documented # setAttr(jsw_body, "massData-I", bodyDef, "inertiaScale") setAttr(jsw_body, "type", bodyDef) setAttr(jsw_body, "awake", bodyDef) # create body body_ref = b2_world.CreateBody(bodyDef) for fixture in jsw_body["fixture"]: add_fixture(body_ref, jsw, fixture)
def __init__(self,bl,tr,tc = None,angle=0): self.dead = False self.tc = tc self.bl = bl self.tr = tr self.weapon_quad = None if tc != None: self.InitPolygons(tc) self.visible = True else: self.visible = False self.bodydef = box2d.b2BodyDef() #This is inefficient, but it doesn't want to grab properly otherwise. Shitty hack but whatever #self.bodydef.allowSleep = False self.midpoint = (tr - bl)*0.5*globals.physics.scale_factor self.bodydef.position = tuple((bl*globals.physics.scale_factor) + self.midpoint) self.bodydef.angle = angle self.shape = self.CreateShape(self.midpoint) if not self.static: self.shape.userData = self if self.filter_group != None: self.shape.filter.groupIndex = self.filter_group self.bodydef.isBullet = self.isBullet self.body = globals.physics.world.CreateBody(self.bodydef) self.shape.density = self.mass self.shape.friction = 0.7 self.shapeI = self.body.CreateShape(self.shape) self.child_joint = None self.parent_joint = None self.ExtraShapes() self.PhysUpdate([]) self.health = self.initial_health
def _ball(self, pos, radius, dynamic=True, density=1.0, restitution=0.16, friction=0.5): # Add a ball without correcting any settings # meaning, pos and vertices are in meters # Define the body x, y = pos bodyDef = box2d.b2BodyDef() bodyDef.position = (x, y) userData = {'color': self.parent.get_color()} bodyDef.userData = userData # Create the Body if not dynamic: density = 0 else: bodyDef.type = box2d.b2_dynamicBody body = self.parent.world.CreateBody(bodyDef) self.parent.element_count += 1 # Add a shape to the Body circleShape = box2d.b2CircleShape() circleShape.radius = radius circleDef = box2d.b2FixtureDef() circleDef.shape = circleShape circleDef.density = density circleDef.restitution = restitution circleDef.friction = friction body.CreateFixture(circleDef) return body
def __init__(self): self._player_maximum_thrust = 2 self._physics_world = Box2D.b2World(gravity=(0,0), doSleep=False, contactListener=ContactDamageInflicter(self)) self._asteroid_shape = Box2D.b2CircleShape() self._asteroid_shape.radius = ASTEROID_RADIUS self._asteroid_fixture = Box2D.b2FixtureDef() self._asteroid_fixture.shape = self._asteroid_shape self._asteroid_fixture.density = 10 self._asteroid_fixture.restitution = 1 self._asteroid_fixture.friction = 1 self._asteroid_fixture.filter.categoryBits = CollisionFilterCategory.ASTEROID self._asteroid_fixture.filter.maskBits = CollisionFilterCategory.ASTEROID | CollisionFilterCategory.PLAYER self._ship_shape = Box2D.b2CircleShape() self._ship_shape.radius = PLAYER_RADIUS ship_fixture = Box2D.b2FixtureDef() ship_fixture.shape = self._ship_shape ship_fixture.density = 5 ship_fixture.restitution = 1 ship_fixture.friction = 1 ship_fixture.filter.categoryBits = CollisionFilterCategory.PLAYER ship_fixture.filter.maskBits = CollisionFilterCategory.ASTEROID | CollisionFilterCategory.BORDER self._player_base_friction = 0.02 self._player_thrust_extra_friction = 0.02 self._player_maximum_turn_thrust = 1 self._thrust_extra_turn_thrust = -0.3 self._base_rotational_friction = 0.1 self._thrust_extra_rotational_friction = 0.05 ship_body_def = Box2D.b2BodyDef() ship_body_def.position = ( 5 + random() * (RIGHT_BORDER_X - 10), 5 + random() * (TOP_BORDER_Y - 10) ) ship_body_def.angle = random() * pi * 2 ship_body_def.linearVelocity = (0,0) ship_body_def.linearDamping = self._player_base_friction ship_body_def.angularVelocity = 0 ship_body_def.angularDamping = self._base_rotational_friction ship_body_def.fixtures = [ship_fixture] ship_body_def.type = Box2D.b2_dynamicBody ship_body_def.allowSleep = False self._player_ship = self._physics_world.CreateBody(ship_body_def) self._asteroids = self._create_starting_asteroids() self._asteroids_to_kill = [] self._asteroid_extra_spawn_accumulator = 0 self._asteroids_avoided_count = 0 self._borders = borders.add_borders(self._physics_world, LEFT_BORDER_X, RIGHT_BORDER_X, BOTTOM_BORDER_Y, TOP_BORDER_Y) self._asteroid_play_space = asteroid_play_space.add_asteroid_play_space(self._physics_world, LEFT_BORDER_X, RIGHT_BORDER_X, BOTTOM_BORDER_Y, TOP_BORDER_Y) self.player_current_health = MAX_PLAYER_HEALTH
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()
def create_body(world, shape_type, position = (0, 0), angle = 0, friction = None, restitution = None, density = None, linear_damping = None, is_sensor = False, fixed_rotation = False, body_type = Box2D.b2_dynamicBody, user_data = None, **kwargs): """Creates a body. All parameters should be self-explanatory with a quick skim of the Box2D manual. **kwargs will be set on the shape type after its construction.""" shape = shape_type() for i, j in kwargs.iteritems(): setattr(shape, i, j) fixture_def = Box2D.b2FixtureDef() if friction is not None: fixture_def.friction = friction if restitution is not None: fixture_def.restitution = restitution if density is not None: fixture_def.density = density fixture_def.shape = shape fixture_def.isSensor = is_sensor body_def = Box2D.b2BodyDef() body_def.type = body_type body_def.position = position body_def.angle = angle body = world.CreateBody(body_def) body.CreateFixture(fixture_def) body.userData = user_data if linear_damping: body.linearDamping = linear_damping body.fixedRotation = fixed_rotation return body
def __init__(self,world,top,size): scenter=(top[0]+(size[0]/2), top[1]+(size[1]/2)) wcenter=world.s2wPos(scenter) extends=world.s2wScale(size) #print 'top: '+str(top) #print 'scenter: '+str(scenter) #print 'wcenter: '+str(wcenter) #print world.w2sPos(wcenter) #print 'size: '+str(size) #print 'extends: '+str(extends) #print world.w2sScale(extends) # Physics walldef=Box2D.b2BodyDef() walldef.position=Box2D.b2Vec2(wcenter[0],wcenter[1]) walldef.userData={} wallbody=world.world.CreateBody(walldef) wallbody.iswall=True wallshape=Box2D.b2PolygonDef() width, height = extends wallshape.SetAsBox(width/2, height/2) wallbody.CreateShape(wallshape) # Display self.image=pygame.Surface(size) self.image.fill((56,71,216)) self.rect = self.image.get_rect() self.rect.topleft=top
def load(self, size): bd=box2d.b2BodyDef() bd.position=self.shape.center[0], self.shape.center[1] sd=box2d.b2PolygonDef() sd.SetAsBox(size[0]/2.0, size[1]/2.0) sd.filter.categoryBits= BallGen.catBits self.body=WorldConfig.world.CreateBody(bd) self.body.CreateShape(sd) self.body.SetMassFromShapes() self.body.userData = self sd.density=2.0 sd.SetAsBox(0.1, 1.8) bd.isBullet=True bd.position=self.body.position.x+1, self.body.position.y+4 body_bar=WorldConfig.world.CreateBody(bd) body_bar.CreateShape(sd) body_bar.SetMassFromShapes() jd= box2d.b2RevoluteJointDef() jd.Initialize(self.body, body_bar, (self.body.position.x+1, self.body.position.y+size[1]/2.0)) jd.maxMotorTorque= 30000.0 jd.motorSpeed = 2* box2d.b2_pi jd.enableMotor = True WorldConfig.world.CreateJoint(jd).getAsType() self.body_bar=body_bar
def __init__(self, screen_size, gravity=( 0.0, -9.0), ppm=100.0, renderer='pygame'): """ Init the world with boundaries and gravity, and init colors. Parameters: screen_size .. (w, h) -- screen size in pixels [int] gravity ...... (x, y) in m/s^2 [float] default: (0.0, -9.0) ppm .......... pixels per meter [float] default: 100.0 renderer ..... which drawing method to use (str) default: 'pygame' Return: class Elements() """ self.set_screenSize(screen_size) self.set_drawingMethod(renderer) # Create Subclasses self.add = add_objects.Add(self) self.callbacks = callbacks.CallbackHandler(self) self.camera = camera.Camera(self) # Gravity + Bodies will sleep on outside self.gravity = gravity self.doSleep = True # Create the World self.world = box2d.b2World(self.gravity, self.doSleep) bodyDef = box2d.b2BodyDef() self.world.groundBody = self.world.CreateBody(bodyDef) # Init Colors self.init_colors() # Set Pixels per Meter self.ppm = ppm
def __init__(self,centre,radius,tc = None,angle=0): self.dead = False self.tc = tc if tc != None: self.InitPolygons(tc) self.visible = True else: self.visible = False self.bodydef = box2d.b2BodyDef() #This is inefficient, but it doesn't want to grab properly otherwise. Shitty hack but whatever self.bodydef.allowSleep = False self.midpoint = radius*math.sqrt(2)*globals.physics.scale_factor self.bodydef.position = box2d.b2Vec2(*(centre*globals.physics.scale_factor)) self.bodydef.angle = angle self.shape = self.CreateShape(radius) self.shape.isSensor = self.is_sensor if not self.static: self.shape.userData = self if self.filter_group != None: self.shape.filter.groupIndex = self.filter_group self.bodydef.isBullet = self.isBullet self.body = globals.physics.world.CreateBody(self.bodydef) self.shape.density = self.mass self.shape.friction = 0.7 self.shapeI = self.body.CreateShape(self.shape) self.child_joint = None self.parent_joint = None self.ExtraShapes() self.PhysUpdate([]) self.health = Gobject.initial_health
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()
def addRevolute(self): sd=box2d.b2PolygonDef() sd.SetAsBox(1, 0.2) sd.density = 2.0 sd.filter.groupIndex=-2 bd1=box2d.b2BodyDef() ppos= self.body.GetWorldCenter() bd1.position = (ppos.x-0.2, ppos.y+0.8) body_arm1 = WorldConfig.world.CreateBody(bd1) body_arm1.CreateShape(sd) body_arm1.SetMassFromShapes() jointDef1 = box2d.b2RevoluteJointDef() jointDef1.Initialize(self.body, body_arm1, (body_arm1.position.x-1, body_arm1.position.y)) # jointDef1.collideConnected = True jointDef1.lowerAngle = 0.1 * box2d.b2_pi # -90 degrees jointDef1.upperAngle = 0.2 * box2d.b2_pi # 45 degrees jointDef1.enableLimit = True # jointDef1.maxMotorTorque= 100.0 jointDef1.motorSpeed = 0.0 jointDef1.enableMotor = True WorldConfig.world.CreateJoint(jointDef1).getAsType() self.bodies.append(body_arm1) bd1.position = (body_arm1.position.x+2, body_arm1.position.y) body_arm2 = WorldConfig.world.CreateBody(bd1) body_arm2.CreateShape(sd) body_arm2.SetMassFromShapes() jointDef1.Initialize(body_arm1, body_arm2, (body_arm2.position.x-1, body_arm2.position.y)) # jointDef1.collideConnected = True jointDef1.lowerAngle = -0.25 * box2d.b2_pi # -90 degrees jointDef1.upperAngle = -0.1 * box2d.b2_pi # 45 degrees jointDef1.enableLimit = True # jointDef1.maxMotorTorque= 1000.0 jointDef1.motorSpeed = 0.0 jointDef1.enableMotor = True WorldConfig.world.CreateJoint(jointDef1).getAsType() self.bodies.append(body_arm2) bd1.position = (body_arm2.position.x+2, body_arm2.position.y) body_arm3 = WorldConfig.world.CreateBody(bd1) body_arm3.CreateShape(sd) body_arm3.SetMassFromShapes() jointDef1.Initialize(body_arm2, body_arm3, (body_arm3.position.x-1, body_arm3.position.y)) # jointDef1.collideConnected = True jointDef1.lowerAngle = -0.25 * box2d.b2_pi # -90 degrees jointDef1.upperAngle = -0.1 * box2d.b2_pi # 45 degrees jointDef1.enableLimit = True # jointDef1.maxMotorTorque= 1000.0 jointDef1.motorSpeed = 0.0 jointDef1.enableMotor = True WorldConfig.world.CreateJoint(jointDef1).getAsType() self.bodies.append(body_arm3)
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
def add_borders(world : Box2D.b2World, left_border : float, right_border : float, bottom_border : float, top_border : float): fixture_defs = _create_fixtures(left_border, right_border, bottom_border, top_border) border_body_def = Box2D.b2BodyDef() border_body_def.fixtures = fixture_defs border_body_def.type = Box2D.b2_staticBody border_body_def.position = (0, 0) return world.CreateBody(border_body_def)
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
def __init__(self, world, x, y, w, h): bodyDef = b2.b2BodyDef() bodyDef.position = (x + w/2.0, y + h/2.0) self.body = world.CreateBody(bodyDef) shapeDef = b2.b2PolygonDef() shapeDef.SetAsBox(w/2.0, h/2.0) shapeDef.friction = 0.4 shapeDef.restitution = 1 self.body.CreateShape(shapeDef) self.body.userData = self
def __init__(self, world, x, y, vertices): bodyDef = b2.b2BodyDef() bodyDef.position = (x, y) self.body = world.CreateBody(bodyDef) shapeDef = b2.b2PolygonDef() shapeDef.setVertices_tuple(vertices) shapeDef.friction = 0.4 shapeDef.restitution = 1 self.body.CreateShape(shapeDef) self.body.userData = self
def load(self): bd=box2d.b2BodyDef() bd.position=self.shape.center[0], self.shape.center[1] sd=box2d.b2PolygonDef() sd.SetAsBox(self.shape.width / 2, self.shape.height / 2) sd.filter.categoryBits= RockGen.catBits self.body=WorldConfig.world.CreateBody(bd) self.body.CreateShape(sd) self.body.userData = self
def load(self, position): bodyDef = box2d.b2BodyDef() bodyDef.position =position bodyDef.isBullet = True body = WorldConfig.world.CreateBody(bodyDef) body.CreateShape(self.getShapeDef()) body.SetMassFromShapes() body.userData = self self.body=body
def create_ground(self, x, y, w, h): props = BodyProperties() sd = box2d.b2PolygonDef() sd.SetAsBox(w, h) bd = box2d.b2BodyDef() bd.position = (x, y) body = self.world.CreateBody(bd) body.CreateShape(sd) body.SetUserData(props) return body
def __init__(self, definition, position=(0,0), angle=0): self.definition = definition bd=box2d.b2BodyDef() bd.position = position bd.angle = angle self.body = definition.world.CreateBody(bd) self.body.CreateShape(definition.shape_def) self.body.SetMassFromShapes()
def __init__(self, world, x, y, vertices): bodyDef = b2.b2BodyDef() bodyDef.position = (x, y) self.body = world.CreateBody(bodyDef) shapeDef = b2.b2PolygonDef() shapeDef.setVertices_tuple(vertices) shapeDef.friction = 0.4 shapeDef.restitution = 1 self.body.CreateShape(shapeDef) self.body.userData = self
def __init__(self, world, x, y, w, h): bodyDef = b2.b2BodyDef() bodyDef.position = (x + w / 2.0, y + h / 2.0) self.body = world.CreateBody(bodyDef) shapeDef = b2.b2PolygonDef() shapeDef.SetAsBox(w / 2.0, h / 2.0) shapeDef.friction = 0.4 shapeDef.restitution = 1 self.body.CreateShape(shapeDef) self.body.userData = self
def createBody(self): bodyDef = b2d.b2BodyDef() bodyDef.position = self.position bodyDef.fixedRotation = self.fixedRotation bodyDef.angle = self.angle bodyDef.linearDamping = self.linearDamping self.body = self.world.CreateBody(bodyDef) self.body.SetUserData(self)
def load(self, size): bd=box2d.b2BodyDef() bd.position=self.shape.center[0], self.shape.center[1] sd=box2d.b2PolygonDef() sd.SetAsBox(size[0]/2.0, size[1]/2.0) sd.filter.categoryBits= Launcher.catBits self.body=WorldConfig.world.CreateBody(bd) self.body.CreateShape(sd) self.body.SetMassFromShapes() self.body.userData = self
def createGround(position=[0, -20]): global world groundBodyDef = Box2D.b2BodyDef() groundBodyDef.position = Box2D.b2Vec2(0, -20) groundBody = world.CreateBody(groundBodyDef) groundBox = Box2D.b2PolygonShape() groundBox.SetAsBox(100, 10) fixture = groundBody.CreateFixturesFromShapes(groundBox, friction=100) return groundBody
def create(self, world, carBody, carPos, cfg): self.maxForwardSpeed = cfg.maxForwardSpeed self.maxBackwardSpeed = cfg.maxBackwardSpeed self.maxDriveForce = cfg.maxDriveForce self.maxLateralImpulse = cfg.maxLateralImpulse bodyDef = b2.b2BodyDef() bodyDef.type = b2.b2_dynamicBody bodyDef.position = b2.b2Vec2(carPos) + b2.b2Vec2(cfg.position) self.body = world.CreateBody(bodyDef) fx = self.body.CreatePolygonFixture(box=(cfg.size.width, cfg.size.height), density=cfg.density)
def construct(self, world, cfg): # Agent body bodyDef = b2.b2BodyDef() bodyDef.type = b2.b2_dynamicBody bodyDef.linearDamping = cfg.linearDamping bodyDef.angularDamping = cfg.angularDamping bodyDef.position = cfg.position self.body = world.CreateBody(bodyDef) self.body.userData = self verts = ((1.5,0.0), (3.0,2.5), (2.8,5.5), (1.0,10.0), (-1.0,10.0), (-2.8,5.5), (-3.0,2.5), (-1.5,0.0) ) self.body.CreatePolygonFixture(vertices=verts, friction=cfg.friction, density=cfg.density, restitution=cfg.restitution ) self.flJoint = self.addWheel(self.frontLeftWheel, world, self.body, cfg.position, cfg.wheels.frontLeft ) self.frJoint = self.addWheel(self.frontRightWheel, world, self.body, cfg.position, cfg.wheels.frontRight ) self.addWheel(self.rearLeftWheel, world, self.body, cfg.position, cfg.wheels.rearLeft ) self.addWheel(self.rearRightWheel, world, self.body, cfg.position, cfg.wheels.rearRight ) # Create Sensor self.addSensor(world, cfg.sensor) # Create the mind or remain mindless if not cfg.mind: return self.mind = programed.MindProgram() self.mind.configure(cfg.mind, self)
def test_helloworld(self): gravity = Box2D.b2Vec2(0, -10) doSleep = True world = Box2D.b2World(gravity, doSleep) groundBodyDef = Box2D.b2BodyDef() groundBodyDef.position = [0, -10] groundBody = world.CreateBody(groundBodyDef) groundBox = Box2D.b2PolygonShape() groundBox.SetAsBox(50, 10) groundBody.CreateFixturesFromShapes(groundBox) bodyDef = Box2D.b2BodyDef() bodyDef.type = Box2D.b2_dynamicBody bodyDef.position = (0, 4) body = world.CreateBody(bodyDef) dynamicBox = Box2D.b2PolygonShape() dynamicBox.SetAsBox(1, 1) fixtureDef = Box2D.b2FixtureDef() fixtureDef.shape = dynamicBox fixtureDef.density = 1 fixtureDef.friction = 0.3 body.CreateFixture(fixtureDef) timeStep = 1.0 / 60 vel_iters, pos_iters = 6, 2 for i in range(60): world.Step(timeStep, vel_iters, pos_iters) world.ClearForces()
def test_helloworld(self): gravity = Box2D.b2Vec2(0, -10) doSleep = True world = Box2D.b2World(gravity, doSleep) groundBodyDef = Box2D.b2BodyDef() groundBodyDef.position = [0, -10] groundBody = world.CreateBody(groundBodyDef) groundBox = Box2D.b2PolygonShape() groundBox.SetAsBox(50, 10) groundBody.CreateFixturesFromShapes(groundBox) bodyDef = Box2D.b2BodyDef() bodyDef.type = Box2D.b2_dynamicBody bodyDef.position = (0, 4) body = world.CreateBody(bodyDef) dynamicBox = Box2D.b2PolygonShape() dynamicBox.SetAsBox(1, 1) fixtureDef = Box2D.b2FixtureDef() fixtureDef.shape = dynamicBox fixtureDef.density = 1 fixtureDef.friction = 0.3 body.CreateFixture(fixtureDef) timeStep = 1.0 / 60 vel_iters, pos_iters = 6, 2 for i in range(60): world.Step(timeStep, vel_iters, pos_iters) world.ClearForces()
def create_character(self, x, y): props = BodyProperties(isCharacter=True) sd = box2d.b2PolygonDef() sd.SetAsBox(10.0, 10.0) sd.density = 1.0 bd = box2d.b2BodyDef() bd.position = (x, y) body = self.world.CreateBody(bd) body.CreateShape(sd) body.SetUserData(props) return body
def aball(world, x, y, r): sd = box2d.b2PolygonShape() sd.SetAsBox(r, r) sd.restitution = 0.05 bd = box2d.b2BodyDef() bd.position = (x, y) body = world.CreateDynamicBody(position=(x, y)) # body = world.CreateBody(bd) groundBoxFixture = box2d.b2FixtureDef(shape=sd) body.CreateFixture(groundBoxFixture) # body.ResetMassData() return body
def __init__(self, wld, robot): self.wld = wld w = wld.w self.robot = robot # Fired by this robot self._fuse = None self._exploding = False r = robot.turret pos = r.position vel = r.linearVelocity ang = r.angle blocalvel = box2d.b2Vec2(conf.bulletspeed, 0) bwvel = r.GetWorldVector(blocalvel) bvel = bwvel + vel #print bvel, bvel.Length() bodyDef = box2d.b2BodyDef() blocalpos = box2d.b2Vec2(.1, 0) bwpos = r.GetWorldVector(blocalpos) bpos = bwpos + pos bodyDef.position = bpos bodyDef.angle = ang bodyDef.isBullet = True bodyDef.linearDamping = 0 bodyDef.userData = {} body = w.CreateBody(bodyDef) #print body #print 'IB', body.isBullet body.linearVelocity = bvel shapeDef = box2d.b2PolygonDef() shapeDef.SetAsBox(.1, .1) shapeDef.density = conf.bullet_density shapeDef.restitution = 0 shapeDef.friction = 0 shapeDef.filter.groupIndex = -robot.n b = body.CreateShape(shapeDef) b.userData = {} body.SetMassFromShapes() body.userData['actor'] = self body.userData['kind'] = 'bullet' body.userData['shooter'] = robot self.body = body v = wld.v.addbullet(pos) self.v = v
class SquareParticle(Particle): def __init__(self, mass, I, loc, vel, ang, ang_vel): Particle.__init__(self, mass, I, loc, vel, ang, ang_vel) self.hp = 150 self.polygon = 1 def display(self): p0 = self.loc + np.array([-self.dis, -self.dis]) p1 = self.loc + np.array([self.dis, -self.dis]) p2 = self.loc + np.array([self.dis, self.dis]) p3 = self.loc + np.array([-self.dis, self.dis]) return p0, p1, p2, p3 bd = b2.b2BodyDef()
def _init_box2d(self): assert (self.x is not None) assert (self.z is not None) # construct box2d world for lidar. self.world = Box2D.b2World() verts = zip(self.x, self.z) nverts = len(verts) for i in range(nverts - 1): p0, p1 = verts[i], verts[i + 1] edge = Box2D.b2EdgeShape(vertices=[p0, p1]) body = Box2D.b2BodyDef( type=Box2D.b2_staticBody, fixtures=Box2D.b2FixtureDef(shape=edge, friction=0), ) self.world.CreateBody(body)
def __init__(self, w, pos, size): walldef = box2d.b2BodyDef() walldef.position = pos walldef.userData = {} wallbod = w.CreateBody(walldef) wallbod.userData['actor'] = None wallbod.userData['kind'] = 'wall' wallbod.iswall = True wallshp = box2d.b2PolygonShape() width, height = size wallshp.SetAsBox(width, height) wallbod.CreatePolygonFixture(box=(width, height), density=1, friction=0.3) v = view.Wall(pos, size) self.v = v
def __init__(self, wld, robot): self.wld = wld w = wld.w self.robot = robot # Fired by this robot self._fuse = None self._exploding = False r = robot.turret pos = r.position vel = r.linearVelocity ang = r.angle blocalvel = box2d.b2Vec2(conf.bulletspeed, 0) bwvel = r.GetWorldVector(blocalvel) bvel = bwvel + vel #print bvel, bvel.length bodyDef = box2d.b2BodyDef(type=box2d.b2_dynamicBody,) blocalpos = box2d.b2Vec2(.1, 0) bwpos = r.GetWorldVector(blocalpos) bpos = bwpos + pos bodyDef.position = bpos bodyDef.angle = ang bodyDef.isBullet = True bodyDef.linearDamping = 0 bodyDef.userData = {} body = w.CreateBody(bodyDef) #print body #print 'IB', body.isBullet body.linearVelocity = bvel body.CreatePolygonFixture( box=(0.1,0.1), friction=0, density=conf.bullet_density, restitution=0, filter = box2d.b2Filter( groupIndex = -robot.n,)) body.userData['actor'] = self body.userData['kind'] = 'bullet' body.userData['shooter'] = robot self.body = body v = wld.v.addbullet(pos) self.v = v
def _create_single_asteroid(self): direction = random() * 2 * pi border_collided_with, collision_point = self._find_border_from_center(direction) # place asteroid beyond border border_offsets = { Borders.LEFT: (-ASTEROID_RADIUS, 0), Borders.TOP: (0, ASTEROID_RADIUS), Borders.RIGHT: (ASTEROID_RADIUS, 0), Borders.BOTTOM: (0, -ASTEROID_RADIUS) } border_offset = border_offsets[border_collided_with] asteroid_spawn_location = tuple(collision_coordinate + offset_coordinate for collision_coordinate, offset_coordinate in zip(collision_point, border_offset)) # make asteroids fly in def create_velocity_generator(start_angle, end_angle): angle_range = end_angle - start_angle def generate_velocity(): chosen_angle = start_angle + random() * angle_range return (cos(chosen_angle) * ASTEROID_SPAWN_SPEED, -sin(chosen_angle) * ASTEROID_SPAWN_SPEED) return generate_velocity border_velocity_generators = { Borders.LEFT: create_velocity_generator (-1 * pi / 4, 1 * pi / 4), Borders.TOP: create_velocity_generator ( 1 * pi / 4, 3 * pi / 4), Borders.RIGHT: create_velocity_generator ( 3 * pi / 4, 5 * pi / 4), Borders.BOTTOM: create_velocity_generator ( 5 * pi / 4, 7 * pi / 4) } velocity = border_velocity_generators[border_collided_with]() max_rotational_velocity = 0.01 asteroid_body_def = Box2D.b2BodyDef() asteroid_body_def.position = asteroid_spawn_location asteroid_body_def.angle = random() * pi * 2 asteroid_body_def.linearVelocity = velocity asteroid_body_def.linearDamping = 0 asteroid_body_def.angularVelocity = (random() * 2 - 1) * max_rotational_velocity asteroid_body_def.angularDamping = 0 asteroid_body_def.fixtures = [self._asteroid_fixture] asteroid_body_def.type = Box2D.b2_dynamicBody asteroid_body_def.allowSleep = False new_asteroid = self._physics_world.CreateBody(asteroid_body_def) return new_asteroid
def __init__(self, w, pos, size): walldef = box2d.b2BodyDef() walldef.position = pos walldef.userData = {} wallbod = w.CreateBody(walldef) wallbod.userData['actor'] = None wallbod.userData['kind'] = 'wall' wallbod.iswall = True wallshp = box2d.b2PolygonDef() width, height = size wallshp.SetAsBox(width, height) wallbod.CreateShape(wallshp) self.body = wallbod self.width = size[0] self.height = size[1] v = view.Wall(pos, size) self.v = v
def abox(world, x, y, w, h): sd = box2d.b2PolygonShape() sd.SetAsBox(w, h) sd.density = 2.0 sd.friction = 0.3 sd.restitution = 0.2 bd = box2d.b2BodyDef() bd.position = (x, y) body = world.CreateDynamicBody(position=(x, y)) # body = world.CreateBody(bd) groundBoxFixture = box2d.b2FixtureDef(shape=sd) body.CreateFixture(groundBoxFixture) body.ResetMassData() body.inertia = .02 body.mass = 1 return body
def geraBody(world, obj): bodyDef = b2.b2BodyDef() bodyDef.position = obj["pos"] bodyDef.type = obj["type"] bodyDef.angle = obj["angle"] body = world.CreateBody(bodyDef) fixDef = b2.b2FixtureDef() fixDef.shape = obj["shape"] fixDef.restitution = obj["restitution"] fixDef.friction = obj["friction"] fixDef.density = obj["density"] body.CreateFixture(fixDef) body.userData = obj return body
def add_body(b2_world, jsw, jsw_body): """add a body described in the json file :param b2_world: an handler to a b2World object :type b2_world: b2World reference :param jsw: dictionary defining all the gropups of data in the json file :type jsw: dict(sting: variant) :param jsw_body: dictionary defining the parameters of the body :type jsw_body: dict(sting: variant) :return: the joint name and the joint reference :rtype: tuple(string, b2Body) """ # create body definition bodyDef = b2.b2BodyDef() # Done with minor issues # missing pybox2d inertiaScale setAttr(jsw, "allowSleep", bodyDef) setAttr(jsw_body, "angle", bodyDef) setAttr(jsw_body, "angularDamping", bodyDef) setAttr(jsw_body, "angularVelocity", bodyDef) setAttr(jsw_body, "awake", bodyDef) setAttr(jsw_body, "bullet", bodyDef) setAttr(jsw_body, "fixedRotation", bodyDef) setAttr(jsw_body, "linearDamping", bodyDef) setB2Vec2Attr(jsw_body, "linearVelocity", bodyDef) setB2Vec2Attr(jsw_body, "position", bodyDef) setAttr(jsw_body, "gravityScale", bodyDef) # pybox2d non documented # setAttr(jsw_body, "massData-I", bodyDef, "inertiaScale") setAttr(jsw_body, "type", bodyDef) setAttr(jsw_body, "awake", bodyDef) # create body body_ref = b2_world.CreateBody(bodyDef) for fixture in jsw_body["fixture"]: add_fixture(body_ref, jsw, fixture) return jsw_body["name"], body_ref
def _buildPhysics(self,width,height,canRotate,isStatic,friction=FRICTION): bodyDef = Box2D.b2BodyDef() bodyDef.position = (self.physicalPosition[0],self.physicalPosition[1]) bodyDef.fixedRotation = not canRotate bodyDef.linearDamping = 0.15 self.body = self.physicsWorld.CreateBody(bodyDef) #self.body.SetUserData(self) shapeDef = Box2D.b2PolygonDef() shapeDef.SetAsBox((width / 2.0) / PIXELS_PER_METER, (height / 2.0) / PIXELS_PER_METER) if isStatic: shapeDef.density = 0 else: shapeDef.density = DENSITY shapeDef.linearDamping = AIR_RESISTANCE shapeDef.friction = friction self.body.CreateShape(shapeDef) self.body.SetMassFromShapes()
def create_obstacle(self, obstacle_spec): obstacle_body_def = Box2D.b2BodyDef() obstacle_body_def.position = (0, 0) obstacle_body = self.world.CreateBody(obstacle_body_def) v = [] for vertex in obstacle_spec["geometry"]['coordinates']: v.append((vertex[0], vertex[1])) obstacle_box = Box2D.b2PolygonShape(vertices=v) obstacle_box_fixture = Box2D.b2FixtureDef(shape=obstacle_box) if "properties" in obstacle_spec: if obstacle_spec["properties"]['collisionGroup']: obstacle_box_fixture.filter.groupIndex = obstacle_spec["properties"]['collisionGroup'] obstacle_body.CreateFixture(obstacle_box_fixture)