self.bodyA = self.world.CreateDynamicBody( position=(0, 10), fixtures=b2FixtureDef( shape=b2PolygonShape(box=(1, 1)), density=1.0) ) self.bodyB = self.world.CreateDynamicBody( position=(0, 5), fixtures=b2FixtureDef( shape=b2CircleShape(radius = 0.5), density=1.0, restitution=0) ) dfn = b2DistanceJointDef( frequencyHz=2.5, dampingRatio=0, bodyA=self.bodyA, bodyB=self.bodyB, anchorA=(0, 10), anchorB=(0, 5), collideConnected=True ) self.world.CreateJoint(dfn) def Step(self, settings): super(Spring, self).Step(settings) if __name__ == "__main__": main(Spring)
scale=(1, 1)) self.car = car self.wheels = wheels self.springs = springs def Keyboard(self, key): if key == Keys.K_a: self.springs[0].motorSpeed = self.speed elif key == Keys.K_s: self.springs[0].motorSpeed = 0 elif key == Keys.K_d: self.springs[0].motorSpeed = -self.speed elif key in (Keys.K_q, Keys.K_e): if key == Keys.K_q: self.hz = max(0, self.hz - 1.0) else: self.hz += 1.0 for spring in self.springs: spring.springFrequencyHz = self.hz def Step(self, settings): super(Car, self).Step(settings) self.viewCenter = (self.car.position.x, 20) self.Print("frequency = %g hz, damping ratio = %g" % (self.hz, self.zeta)) if __name__ == "__main__": main(Car)
def __init__(self, terrain=None): self.max_scores = np.zeros(self.quantity) super().__init__() world = self.world # if terrain == None: # try: # with open("saved_terrain.json") as f: # terrain = parse_terrain(json.load(f)) with open("saved_car.json") as f: super_car = json.load(f) print("Terrain and Car loaded") # print(super_car[0]) # except (IOError, json.JSONDecodeError): # terrain = gen_terrain() terrain, _ = gen_terrain() world.CreateStaticBody(shapes=terrain) self.cars_spec = [(super_car[0], super_car[1])] self.cars = [create_vehicle(world, *car) for car in self.cars_spec] def Step(self, settings): super().Step(settings) self.viewCenter = (self.cars[0][0].position.x, 20) print(self.last_x - self.cars[0][0].position.x) self.last_x = self.cars[0][0].position.x if __name__ == "__main__": main(Simulation)
self.auto = not self.auto elif key == Keys.K_g: self.generate() def Step(self, settings): Framework.Step(self, settings) renderer = self.renderer try: poly = b2PolygonShape(vertices=self.verts) except AssertionError as ex: self.Print('b2PolygonShape failed: %s' % ex) else: self.Print('Valid: %s' % poly.valid) renderer.DrawPolygon([renderer.to_screen(v) for v in self.verts], b2Color(0.9, 0.9, 0.9)) for i, v in enumerate(self.verts): renderer.DrawPoint(renderer.to_screen(v), 2.0, b2Color(0.9, 0.5, 0.5)) x, y = renderer.to_screen(v) self.DrawStringAt(x + 0.05, y + 0.05, '%d' % i) if self.auto: self.generate() if __name__ == "__main__": main(ConvexHull)
super(TwoBallExample, self).__init__() self.world.gravity = (0.0, -10.0) # The boundaries ground = self.world.CreateBody(position=(0, 25.6)) ground.CreateEdgeChain( [(-25.6, -25.6), (-25.6, 25.6), (25.6, 25.6), (25.6, -25.6), (-25.6, -25.6)] ) fixtures = b2FixtureDef(shape=b2CircleShape(radius=1.0), density=1, friction=0.3, restitution=0.5) body = self.world.CreateDynamicBody( position=(0, 10), fixtures=fixtures) def Keyboard(self, key): if not self.body: return if key == Keys.K_w: pass if __name__ == "__main__": main(TwoBallExample)
self.rightJoint = self.world.CreateJoint(rjd) # Ball self.ball = self.world.CreateDynamicBody(fixtures=b2FixtureDef( shape=b2CircleShape(radius=0.2), density=1.0), bullet=True, position=(1, 15)) self.pressed = False def Keyboard(self, key): if key == Keys.K_a: self.pressed = True def KeyboardUp(self, key): if key == Keys.K_a: self.pressed = False def Step(self, settings): if self.pressed: self.leftJoint.motorSpeed = 20 self.rightJoint.motorSpeed = -20 else: self.leftJoint.motorSpeed = -10 self.rightJoint.motorSpeed = 10 super(Pinball, self).Step(settings) if __name__ == "__main__": main(Pinball)
dampingRatio=0.7, ) prevBody = body # And a few random shapes to play with # First a set of triangles, fixture = b2FixtureDef(shape=b2PolygonShape(vertices=[ (-0.5, 0.0), (0.5, 0.0), (0.0, 1.5), ]), density=1.0) for i in range(2): self.world.CreateDynamicBody( position=(-8 + 8 * i, 12), fixtures=fixture, ) # And then a few circles fixture = b2FixtureDef(shape=b2CircleShape(radius=0.5), density=1) for i in range(3): self.world.CreateDynamicBody( position=(-6 + 6 * i, 10), fixtures=fixture, ) if __name__ == "__main__": main(Cantilever)
plank = fixtureDef( shape=polygonShape(box=(0.6, 0.125)), density=20, friction=0.2, ) # Create one Chain (Only the left end is fixed) prevBody = ground y = 25 numPlanks = 30 for i in range(numPlanks): body = self.world.CreateDynamicBody( position=(0.5 + i, y), fixtures=plank, ) # You can try a WeldJoint for a slightly different effect. # self.world.CreateWeldJoint( self.world.CreateRevoluteJoint( bodyA=prevBody, bodyB=body, anchor=(i, y), ) prevBody = body if __name__ == "__main__": main(Chain)
# And the payload that initially sits upon the platform # Reusing the fixture we previously defined above fixture.shape.box = (0.75, 0.75) self.payload = self.world.CreateDynamicBody( position=(0, 8), fixtures=fixture, ) def Keyboard(self, key): if key == Keys.K_d: self.platform.type = b2_dynamicBody elif key == Keys.K_s: self.platform.type = b2_staticBody elif key == Keys.K_k: self.platform.type = b2_kinematicBody self.platform.linearVelocity = (-self.speed, 0) self.platform.angularVelocity = 0 def Step(self, settings): super(BodyTypes, self).Step(settings) if self.platform.type == b2_kinematicBody: p = self.platform.transform.position v = self.platform.linearVelocity if ((p.x < -10 and v.x < 0) or (p.x > 10 and v.x > 0)): v.x = -v.x self.platform.linearVelocity = v if __name__ == "__main__": main(BodyTypes)
from Box2D.examples.framework import (Framework, main) from Box2D import (b2CircleShape, b2EdgeShape, b2FixtureDef) class Restitution (Framework): name = "Restitution example" description = "Note the difference in bounce height of the circles" def __init__(self): super(Restitution, self).__init__() # The ground ground = self.world.CreateStaticBody( shapes=b2EdgeShape(vertices=[(-20, 0), (20, 0)]) ) radius = 1.0 density = 1.0 # The bodies for i, restitution in enumerate([0.0, 0.1, 0.3, 0.5, 0.75, 0.9, 1.0]): self.world.CreateDynamicBody( position=(-10 + 3.0 * i, 20), fixtures=b2FixtureDef( shape=b2CircleShape(radius=radius), density=density, restitution=restitution) ) if __name__ == "__main__": main(Restitution)
for i in range(2, 18, 2): body = self.world.CreateDynamicBody(position=(-10.1, i)) body.CreatePolygonFixture(box=(3.0, 1.0), density=3.0) self.blob_radius = 2 self.bodies, self.joints = create_blob(self.world, (-10, 50), self.blob_radius, circle_radius=0.5) def Keyboard(self, key): if key == Keys.K_w: self.jump = 10000 elif key == Keys.K_a: self.move = -500 elif key == Keys.K_d: self.move = 500 elif key == Keys.K_s: self.move = 0 self.jump = 100 def Step(self, settings): Framework.Step(self, settings) blob_step(self.world, self.bodies, self.blob_radius, self.jump, self.move) self.jump = 100 if __name__ == "__main__": main(GishTribute)
# Platform self.platform = self.world.CreateStaticBody( position=(-5, 5), allowSleep=False, fixtures=b2FixtureDef(friction=0.8, shape=b2PolygonShape(box=(10.0, 5.0)),), ) self.platform_fixture = self.platform.fixtures[0] # Boxes for i in range(5): self.platform = self.world.CreateDynamicBody( position=(-10.0 + 2.0 * i, 7.0), fixtures=b2FixtureDef(density=20.0, shape=b2PolygonShape(box=(0.5, 0.5)),), ) def PreSolve(self, contact, old_manifold): Framework.PreSolve(self, contact, old_manifold) fixture_a, fixture_b = contact.fixtureA, contact.fixtureB if fixture_a == self.platform_fixture: contact.tangentSpeed = 5.0 elif fixture_b == self.platform_fixture: contact.tangentSpeed = -5.0 if __name__ == "__main__": main(ConveyorBelt)
description = "Utilizes b2EdgeShape" def __init__(self): super(EdgeTest, self).__init__() v1 = (-10.0, 0.0) v2 = (-7.0, -1.0) v3 = (-4.0, 0.0) v4 = (0.0, 0.0) v5 = (4.0, 0.0) v6 = (7.0, 1.0) v7 = (10.0, 0.0) shapes = [b2EdgeShape(vertices=[None, v1, v2, v3]), b2EdgeShape(vertices=[v1, v2, v3, v4]), b2EdgeShape(vertices=[v2, v3, v4, v5]), b2EdgeShape(vertices=[v3, v4, v5, v6]), b2EdgeShape(vertices=[v4, v5, v6, v7]), b2EdgeShape(vertices=[v5, v6, v7]) ] ground = self.world.CreateStaticBody(shapes=shapes) box = self.world.CreateDynamicBody( position=(0.5, 0.6), allowSleep=False, shapes=b2PolygonShape(box=(0.5, 0.5)) ) if __name__ == "__main__": main(EdgeTest)
fixtures=b2FixtureDef(shape=b2CircleShape( radius=self.character_radius), density=1.0), ) self.character = body.fixtures[0] body.linearVelocity = (0, -50) self.bottom = ypos - half_height # The bottom of the platform self.top = ypos + half_height # The top of the platform self.state = 'unknown' def PreSolve(self, contact, oldManifold): super(OneSidedPlatform, self).PreSolve(contact, oldManifold) # Make sure we're dealing with the platform and the character if (contact.fixtureA != self.platform and contact.fixtureA != self.character): return if (contact.fixtureB != self.platform and contact.fixtureB != self.character): return # If below the top of the platform, disable the collision response pos = (self.character.body.position.y - self.character_radius + 3.0 * b2_linearSlop) if pos < self.top: contact.enabled = False if __name__ == "__main__": main(OneSidedPlatform)
length = 25.0 point1 = b2Vec2(0, 10) d = (length * cos(self.angle), length * sin(self.angle)) point2 = point1 + d callback = self.callback callback.fixture = None self.world.RayCast(callback, point1, point2) # The callback has been called by this point, and if a fixture was hit it will have been # set to callback.fixture. point1 = self.renderer.to_screen(point1) point2 = self.renderer.to_screen(point2) if callback.fixture: cb_point = self.renderer.to_screen(callback.point) self.renderer.DrawPoint(cb_point, 5.0, self.p1_color) self.renderer.DrawSegment(point1, cb_point, self.s1_color) head = b2Vec2(cb_point) + 0.5 * callback.normal self.renderer.DrawSegment(cb_point, head, self.s2_color) else: self.renderer.DrawSegment(point1, point2, self.s1_color) if not settings.pause or settings.singleStep: self.angle += 0.25 * b2_pi / 180 if __name__ == "__main__": main(EdgeShapes)
for ud in (ud_a, ud_b): obj = ud['obj'] if isinstance(obj, TDTire): tire = obj elif isinstance(obj, TDGroundArea): ground_area = obj if ground_area is not None and tire is not None: if began: tire.add_ground_area(ground_area) else: tire.remove_ground_area(ground_area) def BeginContact(self, contact): self.handle_contact(contact, True) def EndContact(self, contact): self.handle_contact(contact, False) def Step(self, settings): self.car.update(self.pressed_keys, settings.hz) super(TopDownCar, self).Step(settings) tractions = [tire.current_traction for tire in self.car.tires] self.Print('Current tractions: %s' % tractions) if __name__ == "__main__": main(TopDownCar)
) # Compute consistent velocities for new bodies based on cached # velocity. velocity1 = (self.velocity + b2Cross(self.angularVelocity, body.worldCenter - center)) velocity2 = (self.velocity + b2Cross(self.angularVelocity, body2.worldCenter - center)) body.angularVelocity = self.angularVelocity body.linearVelocity = velocity1 body2.angularVelocity = self.angularVelocity body2.linearVelocity = velocity2 def Step(self, settings): super(Breakable, self).Step(settings) if self._break: self.Break() self.broke = True self._break = False if not self.broke: self.velocity = self.body.linearVelocity self.angularVelocity = self.body.angularVelocity def Keyboard(self, key): if key == Keys.K_b and not self.broke: self._break = True if __name__ == "__main__": main(Breakable)
anchorA=p3 + self.offset, anchorB=wheelAnchor + self.offset, ) self.world.CreateDistanceJoint( dampingRatio=0.5, frequencyHz=10, bodyA=body2, bodyB=self.wheel, anchorA=p6 + self.offset, anchorB=wheelAnchor + self.offset, ) self.world.CreateRevoluteJoint( bodyA=body2, bodyB=self.chassis, anchor=p4 + self.offset, ) def Keyboard(self, key): if key == Keys.K_a: self.motorJoint.motorSpeed = -self.motorSpeed elif key == Keys.K_d: self.motorJoint.motorSpeed = self.motorSpeed elif key == Keys.K_s: self.motorJoint.motorSpeed = 0 elif key == Keys.K_m: self.motorJoint.motorEnabled = not self.motorJoint.motorEnabled if __name__ == "__main__": main(TheoJansen)
point2 = point1 + d callback = self.callback_class() self.world.RayCast(callback, point1, point2) # The callback has been called by this point, and if a fixture was hit it will have been # set to callback.fixture. point1 = self.renderer.to_screen(point1) point2 = self.renderer.to_screen(point2) if callback.hit: if hasattr(callback, 'points'): for point, normal in zip(callback.points, callback.normals): draw_hit(point, normal) else: draw_hit(callback.point, callback.normal) else: self.renderer.DrawSegment(point1, point2, self.s1_color) self.Print("Callback: %s" % callback) if callback.hit: self.Print("Hit") if not settings.pause or settings.singleStep: self.angle += 0.25 * b2_pi / 180 if __name__ == "__main__": main(Raycast)
for v in self.shapeB.vertices ], b2Color(0.5, 0.9, 0.5)) # localPoint=(2, -0.1) # rB = transform * localPoint - sweepB.c0 # wB = sweepB.a - sweepB.a0 # vB = sweepB.c - sweepB.c0 # v = vB + b2Cross(wB, rB) # Now, draw shapeB in a different color when they would collide (i.e., # at t=time of impact) This shows that the polygon would rotate upon # collision transform = sweepB.GetTransform(time_of_impact) self.renderer.DrawPolygon([ self.renderer.to_screen(transform * v) for v in self.shapeB.vertices ], b2Color(0.5, 0.7, 0.9)) # And finally, draw shapeB at t=1.0, where it would be if it did not # collide with shapeA In this case, time_of_impact = 1.0, so these # become the same polygon. transform = sweepB.GetTransform(1.0) self.renderer.DrawPolygon([ self.renderer.to_screen(transform * v) for v in self.shapeB.vertices ], b2Color(0.9, 0.5, 0.5)) if __name__ == "__main__": main(TimeOfImpact)
self.createWorld() def Step(self, settings): super(BodyPendulum, self).Step(settings) vv = ((self.pendulum.angle - self._angle_old) / 50) * 10000 self._angle_old = self.pendulum.angle vv2 = ((self.carBody.position.x - self._pendulum_old_x) / 50) * 5000 self._pendulum_old_x = self.carBody.position.x self.pendelumLJoin.maxMotorTorque = 1000 self.pendelumRJoin.maxMotorTorque = 1000 self.pendulum_fuzz.input['join1'] = self.pendulum.angle self.pendulum_fuzz.input['pend1_v'] = vv self.pendulum_fuzz.compute() self.pendulum_fuzz2.input['position'] = self.carBody.position.x self.pendulum_fuzz2.input['v'] = vv2 self.pendulum_fuzz2.compute() xa = self.pendulum_fuzz2.output['motor2'] + self.pendulum_fuzz.output[ 'motor'] self.pendelumLJoin.motorSpeed = xa self.pendelumRJoin.motorSpeed = xa if __name__ == "__main__": main(BodyPendulum)
break class Cloth(Framework): name = "Cloth" description = "(w) Toggle wind" def __init__(self): super(Cloth, self).__init__() self.wind = False self.segment_count = (18, 25) self.body_size = 0.22 cloth_info = create_cloth( self.world, self.segment_count, self.body_size) self.cloth, self.weld_joints, self.dist_joints = cloth_info def Keyboard(self, key): if key == Keys.K_w: self.wind = not self.wind def Step(self, settings): super(Cloth, self).Step(settings) if self.wind: self.Print('Wind enabled') step_cloth(self.world, self.cloth, self.wind, self.body_size, self.segment_count, self.dist_joints) if __name__ == "__main__": main(Cloth)
position=(0, 5 + 1.54 * i), fixtures=fixtures) # For a circle: I = 0.5 * m * r * r ==> r = sqrt(2 * I / m) r = sqrt(2.0 * body.inertia / body.mass) self.world.CreateFrictionJoint( bodyA=ground, bodyB=body, localAnchorA=(0, 0), localAnchorB=(0, 0), collideConnected=True, maxForce=body.mass * gravity, maxTorque=body.mass * r * gravity ) def Keyboard(self, key): if not self.body: return if key == Keys.K_w: f = self.body.GetWorldVector(localVector=(0.0, -200.0)) p = self.body.GetWorldPoint(localPoint=(0.0, 2.0)) self.body.ApplyForce(f, p, True) elif key == Keys.K_a: self.body.ApplyTorque(50.0, True) elif key == Keys.K_d: self.body.ApplyTorque(-50.0, True) if __name__ == "__main__": main(ApplyForce)
# Traverse the contact results. Destroy bodies that # are touching heavier bodies. body_pairs = [(p['fixtureA'].body, p['fixtureB'].body) for p in self.points] for body1, body2 in body_pairs: mass1, mass2 = body1.mass, body2.mass if mass1 > 0.0 and mass2 > 0.0: if mass2 > mass1: nuke_body = body1 else: nuke_body = body2 if nuke_body not in nuke: nuke.append(nuke_body) # Destroy the bodies, skipping duplicates. for b in nuke: print("Nuking:", b) self.world.DestroyBody(b) nuke = None super(CollisionProcessing, self).Step(settings) if __name__ == "__main__": main(CollisionProcessing)
bodyA = self.world.CreateDynamicBody( position=(-10, y), fixtures=fixtureDef(shape=polygonShape(box=(a, b)), density=5.0), ) bodyB = self.world.CreateDynamicBody( position=(10, y), fixtures=fixtureDef(shape=polygonShape(box=(a, b)), density=5.0), ) self.pulley = self.world.CreatePulleyJoint( bodyA=bodyA, bodyB=bodyB, anchorA=(-10.0, y + b), anchorB=(10.0, y + b), groundAnchorA=(-10.0, y + b + L), groundAnchorB=(10.0, y + b + L), ratio=1.5, ) def Step(self, settings): super(Pulley, self).Step(settings) ratio = self.pulley.ratio L = self.pulley.length1 + self.pulley.length2 * ratio self.Print('L1 + %4.2f * L2 = %4.2f' % (ratio, L)) if __name__ == "__main__": main(Pulley)
prevBody = body extraLength = 0.01 self.rd = rd = b2RopeJointDef(bodyA=ground, bodyB=body, maxLength=N - 1.0 + extraLength, localAnchorA=(0, y), localAnchorB=(0, 0)) self.rope = self.world.CreateJoint(rd) def Step(self, settings): super(Rope, self).Step(settings) if self.rope: self.Print('Rope ON') else: self.Print('Rope OFF') def Keyboard(self, key): if key == Keys.K_j: if self.rope: self.world.DestroyJoint(self.rope) self.rope = None else: self.rope = self.world.CreateJoint(self.rd) if __name__ == "__main__": main(Rope)
self.arm.target_pose = [ p[0], p[1], self.wristAngle, self.arm_angles[-2], self.arm_angles[-1] ] def Keyboard(self, key): for letter in ascii_lowercase: if key == eval("Keys.K_" + letter): self.alphabet[ascii_lowercase.index(letter)] = True if self.alphabet[ascii_lowercase.index('a')]: self.recording = True if self.alphabet[ascii_lowercase.index('s')]: self.recording = False if self.alphabet[ascii_lowercase.index('d')]: print("reset") self.reset = True def MouseDown(self, p): self.arm.target_pose[0] = p[0] self.arm.target_pose[1] = p[1] def KeyboardUp(self, key): for letter in ascii_lowercase: if key == eval("Keys.K_" + letter): self.alphabet[ascii_lowercase.index(letter)] = False if __name__ == "__main__": main(ArmSim)
for i in range(rows): self.world.CreateDynamicBody( fixtures=box, position=(box_start + box_space * j, 0.752 + 1.54 * i)) self.world.CreateDynamicBody( fixtures=circle, position=(circle_start + circle_space * j, 0.752 + 1.54 * i)) def Step(self, settings): super(VerticalStack, self).Step(settings) def Keyboard(self, key): if key == Keys.K_b: if self.bullet: self.world.DestroyBody(self.bullet) self.bullet = None circle = b2FixtureDef(shape=b2CircleShape(radius=0.25), density=20, restitution=0.05) self.bullet = self.world.CreateDynamicBody( position=(-31, 5), bullet=True, fixtures=circle, linearVelocity=(400, 0), ) if __name__ == "__main__": main(VerticalStack)
def dynamic_positions(): x = b2Vec2(-7.0, 0.75) deltaX = (0.5625, 1.25) deltaY = (1.125, 0.0) for i in range(count): y = x.copy() for j in range(i, count): yield y y += deltaY x += deltaX for pos in dynamic_positions(): self.world.CreateDynamicBody(position=pos, fixtures=b2FixtureDef( shape=b2PolygonShape(box=(a, a)), density=5)) def Step(self, settings): super(Tiles, self).Step(settings) cm = self.world.contactManager height = cm.broadPhase.treeHeight leafCount = cm.broadPhase.proxyCount minNodeCount = 2 * leafCount - 1 minHeight = ceil(log(float(minNodeCount)) / log(2)) self.Print('Dynamic tree height=%d, min=%d' % (height, minHeight)) if __name__ == "__main__": main(Tiles)
h = (0, a) p = parent.position + local_anchor - h fixture = b2FixtureDef(shape=b2PolygonShape(box=(0.25 * a, a)), density=density) body = self.world.CreateDynamicBody(position=p, fixtures=fixture) if depth == self.max_depth: return body a1 = (offset, -a) a2 = (-offset, -a) body1 = self.add_node(body, a1, depth + 1, 0.5 * offset, a) body2 = self.add_node(body, a2, depth + 1, 0.5 * offset, a) self.world.CreateRevoluteJoint(bodyA=body, bodyB=body1, localAnchorA=a1, localAnchorB=h) self.world.CreateRevoluteJoint(bodyA=body, bodyB=body2, localAnchorA=a2, localAnchorB=h) return body if __name__ == "__main__": main(Mobile)