def setup_world(self): self.worldAABB = box2d.b2AABB() self.worldAABB.lowerBound = (-2000.0, -2000.0) self.worldAABB.upperBound = (2000.0, 2000.0) self.gravity = (0.0, -9.81) doSleep = False self.world = box2d.b2World(self.worldAABB, self.gravity, doSleep)
def obtener_cuerpos_en(self, x, y): """Retorna una lista de cuerpos que se encuentran en la posicion (x, y) o retorna una lista vacia []. :param x: posición horizontal del punto a analizar. :param y: posición vertical del punto a analizar. """ AABB = box2d.b2AABB() f = 1 AABB.lowerBound = (x - f, y - f) AABB.upperBound = (x + f, y + f) cuantos, cuerpos = self.mundo.Query(AABB, 2) if cuantos == 0: return [] lista_de_cuerpos = [] for s in cuerpos: cuerpo = s.GetBody() if s.TestPoint(cuerpo.GetXForm(), (x, y)): lista_de_cuerpos.append(cuerpo) return lista_de_cuerpos
def __init__(self): self.count = 1000 self.force = 10 self.robots = {} self.bullets = [] self.sprites = {} self.to_destroy = [] halfx = 30 self.ahalfx = 20 halfy = 25 self.ahalfy = 20 gravity = (0, 0) doSleep = True self.timeStep = 1.0 / 60.0 self.velIterations = 10 self.posIterations = 8 aabb = box2d.b2AABB() aabb.lowerBound = (-halfx, -halfy) aabb.upperBound = (halfx, halfy) self.w = box2d.b2World(gravity, doSleep) self.makearena()
def obtener_cuerpos_en(self, x, y): """Retorna una lista de cuerpos que se encuentran en la posicion (x, y) o retorna una lista vacia []. :param x: posición horizontal del punto a analizar. :param y: posición vertical del punto a analizar. """ AABB = box2d.b2AABB() f = 1 AABB.lowerBound = (x-f, y-f) AABB.upperBound = (x+f, y+f) cuantos, cuerpos = self.mundo.Query(AABB, 2) if cuantos == 0: return [] lista_de_cuerpos = [] for s in cuerpos: cuerpo = s.GetBody() if s.TestPoint(cuerpo.GetXForm(), (x, y)): lista_de_cuerpos.append(cuerpo) return lista_de_cuerpos
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 __init__(self): self.count = 1000 self.force = 10 self.robots = {} self.bullets = [] self.sprites = {} self.walls = [] self.to_destroy = [] halfx = 30 self.ahalfx = 20 halfy = 25 self.ahalfy = 20 gravity = (0, 0) doSleep = True self.timeStep = 1.0 / 60.0 self.velIterations = 10 self.posIterations = 8 aabb = box2d.b2AABB() aabb.lowerBound = (-halfx, -halfy) aabb.upperBound = (halfx, halfy) self.w = box2d.b2World(aabb, gravity, doSleep) self.w.GetGroundBody().SetUserData({'actor': None}) self.makearena()
def __init__(self, **kw): super(Framework, self).__init__(**kw) # Initialize the text display group self.textGroup = grText(self) # Load the font and record the screen dimensions self.font = pyglet.font.load(self.fontname, self.fontsize) self.screenSize = box2d.b2Vec2(self.width, self.height) # Box2D Initialization self.worldAABB = box2d.b2AABB() self.worldAABB.lowerBound = (-200.0, -100.0) self.worldAABB.upperBound = ( 200.0, 200.0) gravity = (0.0, -10.0) doSleep = True self.world = box2d.b2World(self.worldAABB, gravity, doSleep) self.destructionListener = fwDestructionListener() self.boundaryListener = fwBoundaryListener() self.contactListener = fwContactListener() self.debugDraw = fwDebugDraw() self.debugDraw.surface = self.screen self.destructionListener.test = self self.boundaryListener.test = self self.contactListener.test = self self.world.SetDestructionListener(self.destructionListener) self.world.SetBoundaryListener(self.boundaryListener) self.world.SetContactListener(self.contactListener) self.world.SetDebugDraw(self.debugDraw) self._viewCenter = box2d.b2Vec2(0,10.0)
def __init__(self): self.count = 1000 self.force = 10 self.tanks = {} self.bullets = [] self.sprites = {} self.to_destroy = [] halfx = 30 self.ahalfx = 20 halfy = 25 self.ahalfy = 20 gravity = (0, 0) doSleep = True self.timeStep = 1.0 / 60.0 self.velIterations = 10 self.posIterations = 8 aabb = box2d.b2AABB() aabb.lowerBound = (-halfx, -halfy) aabb.upperBound = (halfx, halfy) self.w = box2d.b2World(aabb, gravity, doSleep) self.w.GetGroundBody().SetUserData({'actor': None}) self.makearena()
def query(self, lower, upper): callback = QueryCallback() AABB = Box2D.b2AABB() AABB.lowerBound = lower AABB.upperBound = upper self.world.QueryAABB(callback, AABB) return callback
def MouseDown(self, p): """ Indicates that there was a left click at point p (world coordinates) """ if self.mouseJoint != None: return # Make a small box. aabb = box2d.b2AABB() d = box2d.b2Vec2(0.001, 0.001) aabb.lowerBound = p - d aabb.upperBound = p + d # Query the world for overlapping shapes. body = None k_maxCount = 10 (count, shapes) = self.world.Query(aabb, k_maxCount) for shape in shapes: shapeBody = shape.GetBody() if shapeBody.IsStatic() == False and shapeBody.GetMass() > 0.0: if shape.TestPoint(shapeBody.GetXForm(), p): # is it inside? body = shapeBody break if body: md = box2d.b2MouseJointDef() md.body1 = self.world.GetGroundBody() md.body2 = body md.target = p md.maxForce= 1000.0 * body.GetMass() self.mouseJoint = self.world.CreateJoint(md) body.WakeUp()
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 bodiesAtPoint(world, pt, includeStatic=False, includeSensor=False, maxBodies=1000): ''' Find up to maxBodies located at pt ''' # modified from the Elements source (formerly: http://elements.linuxuser.at) # see NOTE above # thanks guys! sx, sy = pt f = 0.01 aabb = box2d.b2AABB() aabb.lowerBound.Set(sx - f, sy - f); aabb.upperBound.Set(sx + f, sy + f); amount, shapes = world.Query(AABB, maxBodies) bodies = set() if amount == 0: return bodies else: for s in shapes: if s.IsSensor() and not includeSensor: continue body = s.GetBody() if not includeStatic: if body.IsStatic() or body.GetMass() == 0.0: continue if s.TestPoint(body.GetXForm(), (sx, sy)): bodies.append(body) return bodies
def get_bodies_at_pos(self, search_point, include_static=False, area=0.01): """ Check if given point (screen coordinates) is inside any body. If yes, return all found bodies, if not found return False """ sx, sy = self.to_world(search_point) sx /= self.ppm sy /= self.ppm f = area / self.camera.scale_factor AABB = box2d.b2AABB() AABB.lowerBound = (sx - f, sy - f) AABB.upperBound = (sx + f, sy + f) amount, shapes = self.world.Query(AABB, 2) if amount == 0: return False else: bodylist = [] for s in shapes: body = s.GetBody() if not include_static: if body.IsStatic() or body.GetMass() == 0.0: continue if s.TestPoint(body.GetXForm(), (sx, sy)): bodylist.append(body) return bodylist
def create_mouse_joint(self, x, y): """ create a mouse joint to the body on world coordinates x, y """ if self.mouse_joint: return world_coord = box2d.b2Vec2(self.debugDraw.screen_to_world((x, y))) aabb = box2d.b2AABB() aabb.lowerBound = world_coord - (0.001, 0.001) aabb.upperBound = world_coord + (0.001, 0.001) max_count = 10 count, shapes = self.world.Query(aabb, max_count) body = (body for shape, body in ((shape, shape.GetBody()) for shape in shapes) if not body.IsStatic() and body.GetMass() > 0.0 and shape.TestPoint(body.GetXForm(), world_coord)) body = list(itertools.islice(body, 1)) body = body[0] if len(body) == 1 else None if body: md = box2d.b2MouseJointDef() md.body1 = self.world.GetGroundBody() md.body2 = body md.target = world_coord md.maxForce = 1000 * body.GetMass() self.mouse_joint = self.world.CreateJoint(md) body.WakeUp()
def get_bodies_at_pos(self, search_point, include_static=False, area=0.01): """ Check if given point (screen coordinates) is inside any body. If yes, return all found bodies, if not found return False """ sx, sy = self.to_world(search_point) sx /= self.ppm sy /= self.ppm f = area/self.camera.scale_factor AABB=box2d.b2AABB() AABB.lowerBound = (sx-f, sy-f) AABB.upperBound = (sx+f, sy+f) amount, shapes = self.world.Query(AABB, 2) if amount == 0: return False else: bodylist = [] for s in shapes: body = s.GetBody() if not include_static: if body.IsStatic() or body.GetMass() == 0.0: continue if s.TestPoint(body.GetXForm(), (sx, sy)): bodylist.append(body) return bodylist
def get_bodies_at_pos(self, search_point, include_static=False, area=0.01): """ Check if given point (screen coordinates) is inside any body. If yes, return all found bodies, if not found return False """ sx, sy = self.to_world(search_point) sx /= self.ppm sy /= self.ppm f = area / self.camera.scale_factor AABB = box2d.b2AABB() AABB.lowerBound = (sx - f, sy - f) AABB.upperBound = (sx + f, sy + f) query_cb = Query_CB() self.world.QueryAABB(query_cb, AABB) bodylist = [] for s in query_cb.fixtures: body = s.body if body is None: continue if not include_static: if body.type == box2d.b2_staticBody or body.mass == 0.0: continue if s.TestPoint((sx, sy)): bodylist.append(body) return bodylist
def get_bodies_at_pos(self, search_point, include_static=False, area=0.01): """ Check if given point (screen coordinates) is inside any body. If yes, return all found bodies, if not found return False """ sx, sy = self.to_world(search_point) sx /= self.ppm sy /= self.ppm f = area / self.camera.scale_factor AABB = box2d.b2AABB() AABB.lowerBound = (sx - f, sy - f) AABB.upperBound = (sx + f, sy + f) query_cb = Query_CB() self.world.QueryAABB(query_cb, AABB) bodylist = [] for f in query_cb.fixtures: body = f.body if body is None: continue if not include_static: if body.type == box2d.b2_staticBody or body.mass == 0.0: continue if f.TestPoint((sx, sy)): bodylist.append(body) return bodylist
def Grapple(self,pos): if self.joint: self.UnGrapple() return diff = pos - self.GetPos() distance,angle = cmath.polar(complex(diff.x,diff.y)) angle = (angle - (math.pi/2) - self.GetAngle())%(math.pi*2) #0 = pi*2 is straight ahead, pi is behind. #so 0.75 pi to 1.25 pi is allowed if not (angle <= self.min_shoot and angle >= self.max_shoot): return if distance > self.max_grapple: return #We need to determine if this point is in any objects... #We'll create a small AABB around the point, and get the list of potentially intersecting shapes, #then test each one to see if the point is inside it aabb = box2d.b2AABB() phys_pos = pos*self.physics.scale_factor #First of all make sure it's not inside us trans = box2d.b2XForm() trans.SetIdentity() p = phys_pos - Point(*self.body.position) if self.shapeI.TestPoint(trans,tuple(p)): return aabb.lowerBound.Set(phys_pos.x-0.1,phys_pos.y-0.1) aabb.upperBound.Set(phys_pos.x+0.1,phys_pos.y+0.1) (count,shapes) = self.physics.world.Query(aabb,10) for shape in shapes: trans = box2d.b2XForm() trans.SetIdentity() p = phys_pos - Point(*shape.GetBody().position) if shape.TestPoint(trans,tuple(p)): self.touching = shape self.contact = p break else: self.touching = None self.contact = None if not self.touching: return globals.sounds.grapple.play() #Tell the other body that it's in a joint with us so that target = self.touching.userData if target == None: self.touching = None self.contact = None return target.parent_joint = self self.child_joint = target joint = box2d.b2DistanceJointDef() joint.Initialize(self.body,self.touching.GetBody(),self.body.GetWorldCenter(),tuple(phys_pos)) joint.collideConnected = True self.joint = self.physics.world.CreateJoint(joint) self.grappled = True self.grapple_quad.Enable()
def create_physics_world(self, size): # create world worldAABB = box2d.b2AABB() worldAABB.lowerBound = (-10, -10) worldAABB.upperBound = (size[0] + 10, size[1] + 10) gravity = box2d.b2Vec2(0.0, 0.0) doSleep = True world = box2d.b2World(worldAABB, gravity, doSleep) return world
def __init__(self): # Box2D Initialization self.worldAABB=box2d.b2AABB() self.worldAABB.lowerBound = (-200.0, -100.0) self.worldAABB.upperBound = ( 200.0, 200.0) gravity = (0.0, -10.0) doSleep = True self.world = box2d.b2World(self.worldAABB, gravity, doSleep) self.destructionListener = fwDestructionListener() self.boundaryListener = fwBoundaryListener() self.contactListener = fwContactListener() self.debugDraw = fwDebugDraw() self.destructionListener.test = self self.boundaryListener.test = self self.contactListener.test = self self.world.SetDestructionListener(self.destructionListener) self.world.SetBoundaryListener(self.boundaryListener) self.world.SetContactListener(self.contactListener) self.world.SetDebugDraw(self.debugDraw) # Pygame Initialization if fwSettings.onlyInit: # testing mode doesn't initialize pygame return pygame.init() self.screen = pygame.display.set_mode( (640,480) ) self.debugDraw.surface = self.screen self.screenSize = box2d.b2Vec2(*self.screen.get_size()) caption= "TEST (%3d X %3d) " % (self.screenSize.x, self.screenSize.y) pygame.display.set_caption(caption) try: self.font = pygame.font.Font(None, 15) except IOError: try: self.font = pygame.font.Font("freesansbold.ttf", 15) except IOError: print "Unable to load default font or 'freesansbold.ttf'" print "Disabling text drawing." self.DrawString = lambda x,y,z: 0 # GUI Initialization self.gui_app = gui.App() self.gui_table=fwGUI(self.settings) container = gui.Container(align=1,valign=-1) container.add(self.gui_table,0,0) self.gui_app.init(container) self.viewCenter = (0,10.0*20.0)
def draw(self, camera): world = engine.get().box2d_world query = DrawQueryCallback(camera) rect = rectangle.from_entity(camera.entity).bounding_rect() aabb = Box2D.b2AABB(lowerBound=Box2D.b2Vec2(rect.bottom_left),upperBound=Box2D.b2Vec2(rect.top_right)) world.QueryAABB(query, aabb)
def queryPoint(p): aabb = Box2D.b2AABB(lowerBound=(p[0] - 0.001, p[1] - 0.001), upperBound=(p[0] + 0.001, p[1] + 0.001)) # Query the world for overlapping shapes. query = fwQueryCallback(p) world.QueryAABB(query, aabb) if query.fixture: body = query.fixture.body
def constructWorld(self): doSleep = False worldAABB=b2d.b2AABB() worldAABB.lowerBound = (-20, -20) worldAABB.upperBound = (self.size[0]+20, self.size[1]+20) self.world = b2d.b2World(worldAABB, self.original_gravity, doSleep) self.contactListener = ContactListener(self) self.world.SetContactListener(self.contactListener)
def __init__(self): # Box2D Initialization self.worldAABB = box2d.b2AABB() self.worldAABB.lowerBound = (-200.0, -100.0) self.worldAABB.upperBound = (200.0, 200.0) gravity = (0.0, -10.0) doSleep = True self.world = box2d.b2World(self.worldAABB, gravity, doSleep) self.destructionListener = fwDestructionListener() self.boundaryListener = fwBoundaryListener() self.contactListener = fwContactListener() self.debugDraw = fwDebugDraw() self.destructionListener.test = self self.boundaryListener.test = self self.contactListener.test = self self.world.SetDestructionListener(self.destructionListener) self.world.SetBoundaryListener(self.boundaryListener) self.world.SetContactListener(self.contactListener) self.world.SetDebugDraw(self.debugDraw) # Pygame Initialization if fwSettings.onlyInit: # testing mode doesn't initialize pygame return pygame.init() caption = "Python Box2D Testbed - " + self.name pygame.display.set_caption(caption) self.screen = pygame.display.set_mode((1000, 700)) self.debugDraw.surface = self.screen self.screenSize = box2d.b2Vec2(*self.screen.get_size()) try: self.font = pygame.font.Font(None, 24) except IOError: try: self.font = pygame.font.Font("freesansbold.ttf", 24) except IOError: print "Unable to load default font or 'freesansbold.ttf'" print "Disabling text drawing." self.DrawString = lambda x, y, z: 0 # GUI Initialization self.gui_app = gui.App() self.gui_table = fwGUI(self.settings) container = gui.Container(align=1, valign=-1) container.add(self.gui_table, 0, 0) self.gui_app.init(container) self.viewCenter = (0, 10.0 * 20.0)
def bodiesInRegion(world, region, maxBodies=1000): ''' Find up to maxBodies located in a region: (leftBottom, rightTop) ''' aabb = box2d.b2AABB() aabb.lowerBound.Set(region[0]) aabb.upperBound.Set(region[1]) count, shapes = world.Query(aabb, maxBodies) bodies = set() for shape in shapes: bodies.add(shape.GetBody()) return bodies
def init(width=Game.WINDOW_WIDTH, height=Game.WINDOW_HEIGHT, window_per_world=20.0): WorldConfig.WINDOW_PER_WORLD = window_per_world worldAABB = box2d.b2AABB() worldAABB.lowerBound.Set(0, 0) WorldConfig.WORLD_WIDTH= width / window_per_world WorldConfig.WORLD_HEIGHT=height/ window_per_world worldAABB.upperBound.Set(WorldConfig.WORLD_WIDTH, WorldConfig.WORLD_HEIGHT) WorldConfig.world = box2d.b2World(worldAABB, WorldConfig.gravity, WorldConfig.doSleep) WorldConfig.contactListener = fwContactListener() WorldConfig.world.SetContactListener(WorldConfig.contactListener)
def __init__(self): worldAABB=box2d.b2AABB() worldAABB.lowerBound = (-8, -8) worldAABB.upperBound = (30, 30) self.world = box2d.b2World(worldAABB, self.gravity, self.doSleep) floor_bodyDef = box2d.b2BodyDef() floor_bodyDef.position = (14, 8) floor_bodyDef.userData = self floor_body = self.world.CreateBody(floor_bodyDef) floor_shapeDef = box2d.b2PolygonDef() floor_shapeDef.SetAsBox(16, 1) floor_body.CreateShape(floor_shapeDef)
def pickActor(self, pos): aabb = b2d.b2AABB() x,y = pos eps = 1e-5 aabb.lowerBound = (x-eps, y-eps) aabb.upperBound = (x+eps, y+eps) num, shapes = self.world.Query(aabb, 10) if num == 0: return for shape in shapes: actor = shape.GetBody().userData if actor.isPointInside(pos): return actor
def GetObjectAtPoint(self,pos): aabb = box2d.b2AABB() phys_pos = pos*self.scale_factor aabb.lowerBound.Set(phys_pos.x-0.1,phys_pos.y-0.1) aabb.upperBound.Set(phys_pos.x+0.1,phys_pos.y+0.1) (count,shapes) = self.world.Query(aabb,10) for shape in shapes: trans = box2d.b2XForm() trans.SetIdentity() p = phys_pos - Point(*shape.GetBody().position) if shape.TestPoint(trans,tuple(p)): return shape.userData return None
def getReadings(self): p = self.player.body.position aabb = Box2D.b2AABB( lowerBound=p - (self.radius, self.radius), upperBound=p + (self.radius, self.radius)) # Query the world for overlapping shapes. query = ProximitySensorCallback(p, self.radius) self.player.map.world.QueryAABB(query, aabb) return [dict( object_type=result.get_type(), id=result.get_id(), **result.get_full_position()) for result in query.result if result is not self.player]
def init_physics(self): # Box2D Initialization self.worldAABB = box2d.b2AABB() self.worldAABB.lowerBound = (-self.window.width*4, -self.window.height*4) self.worldAABB.upperBound = (self.window.width*8, self.window.height*8) gravity = (0.0, -21.0) doSleep = True self.contact_listener = ContactListener() self.world = box2d.b2World(self.worldAABB, gravity, doSleep) self.world.SetContactListener(self.contact_listener) self.build_map_container() self.build_ground() self.build_objects() self.weather = Weather(self)
def __init__(self,parent): self.contact_listener = MyContactListener() self.contact_listener.physics = self self.parent = parent self.worldAABB=box2d.b2AABB() self.worldAABB.lowerBound = (-100,-globals.screen.y-100) self.worldAABB.upperBound = (100 + self.parent.absolute.size.x*self.scale_factor,100 + self.parent.absolute.size.y*self.scale_factor + 100) self.gravity = (0,-10) self.doSleep = True self.world = box2d.b2World(self.worldAABB, self.gravity, self.doSleep) self.world.SetContactListener(self.contact_listener) self.timeStep = 1.0 / 60.0 self.velocityIterations = 10 self.positionIterations = 8 self.objects = []
def load(self): worldBB = b2.b2AABB() worldBB.lowerBound = (-10, -10) worldBB.upperBound = (30, 30) self.world = b2.b2World(worldBB, (0, 0), True) self.contactListener = MyContactListener() self.world.SetContactListener(self.contactListener) self.bgimage = pygame.image.load("table.png").convert() #top left PolyWall(self.world, 0, -1, ((-0.3, 0), (7.5, 0), (7.5, 1), (0.7, 1))) #top right PolyWall(self.world, 0, -1, ((8.5, 0), (16.3, 0), (15.3, 1), (8.5, 1))) #bottom left PolyWall(self.world, 0, 8, ((0.7, 0), (7.5, 0), (7.5, 1), (-0.3, 1))) #bottom right PolyWall(self.world, 0, 8, ((8.5, 0), (15.3, 0), (16.3, 1), (8.5, 1))) #left PolyWall(self.world, -1, 0, ((0, -0.3), (1, 0.7), (1, 7.3), (0, 8.3))) #right PolyWall(self.world, 16, 0, ((0, 0.7), (1, -0.3), (1, 8.3), (0, 7.3))) Pocket(self.world, -0.3, -0.3) Pocket(self.world, 8, -0.5) Pocket(self.world, 16.4, -0.3) Pocket(self.world, -0.3, 8.4) Pocket(self.world, 8, 8.5) Pocket(self.world, 16.4, 8.4) Ball.shadow_image = pygame.image.load( "ball-shadow.png").convert_alpha() Ball.shading_image = pygame.image.load( "ball-shading.png").convert_alpha() Ball(self.world, 1, 10, 4) Ball(self.world, 2, 10.5, 4.3) Ball(self.world, 3, 10.5, 3.7) Ball(self.world, 4, 11, 4.6) Ball(self.world, 9, 11, 4) Ball(self.world, 5, 11, 3.4) Ball(self.world, 6, 11.5, 4.3) Ball(self.world, 7, 11.5, 3.7) Ball(self.world, 8, 12, 4) self.cue = Ball(self.world, 0, 4, 4) self.ready = True
def __init__(self): super(GameModel,self).__init__() self.acting = False self.character = None self.ground = None # Box2D Initialization self.zoom = 50.0 self.worldAABB=box2d.b2AABB() self.worldAABB.lowerBound = (-200.0, -100.0) self.worldAABB.upperBound = ( 200.0, 200.0) gravity = (0.0, -10.0) doSleep = True self.world = box2d.b2World(self.worldAABB, gravity, doSleep) settings = fwSettings self.settings = settings self.flag_info = [ ('draw_shapes', settings.drawShapes, box2d.b2DebugDraw.e_shapeBit), ('draw_joints', settings.drawJoints, box2d.b2DebugDraw.e_jointBit), ('draw_controlers', settings.drawControllers, box2d.b2DebugDraw.e_controllerBit), ('draw_core_shapes', settings.drawCoreShapes, box2d.b2DebugDraw.e_coreShapeBit), ('draw_aabbs', settings.drawAABBs, box2d.b2DebugDraw.e_aabbBit), ('draw_obbs', settings.drawOBBs, box2d.b2DebugDraw.e_obbBit), ('draw_pairs', settings.drawPairs, box2d.b2DebugDraw.e_pairBit), ('draw_center_of_masses', settings.drawCOMs, box2d.b2DebugDraw.e_centerOfMassBit),] # Create hero self.character = self.create_character(200, 800, 50, 100) self.character.SetMassFromShapes() self.character.linearVelocity = (1, 0) if self.settings.debugLevel: print self.character # Create ground self.ground = self.create_ground(500, 0, 1000, 20) self.wall = self.create_ground(400, 20, 100, 20) self.wall2 = self.create_ground(600, 100, 100, 20)
def __init__(self,name): self.allObjects = pygame.sprite.LayeredDirty() bgimage = ImageHandler()[name] self.physicalSize = Vect(float(bgimage.get_width())/PIXELS_PER_METER,float(bgimage.get_height())/PIXELS_PER_METER) self.drawDebug = False world_bounds = Box2D.b2AABB() world_bounds.lowerBound = (0,0) world_bounds.upperBound = (self.physicalSize[0],self.physicalSize[1]) doSleep = True self.physicsWorld = Box2D.b2World(world_bounds, GRAVITY, doSleep) self.listener = MyListener() self.listener.test = self self.physicsWorld.SetContactListener(self.listener) self.points=[] self.background = None
def load(self): worldBB = b2.b2AABB() worldBB.lowerBound = (-10, -10) worldBB.upperBound = (30, 30) self.world = b2.b2World(worldBB, (0, 0), True) self.contactListener = MyContactListener() self.world.SetContactListener(self.contactListener) self.bgimage = pygame.image.load("table.png").convert() #top left PolyWall(self.world, 0, -1, ((-0.3, 0), (7.5, 0), (7.5, 1), (0.7, 1))) #top right PolyWall(self.world, 0, -1, ((8.5, 0), (16.3, 0), (15.3, 1), (8.5, 1))) #bottom left PolyWall(self.world, 0, 8, ((0.7, 0), (7.5, 0), (7.5, 1), (-0.3, 1))) #bottom right PolyWall(self.world, 0, 8, ((8.5, 0), (15.3, 0), (16.3, 1), (8.5, 1))) #left PolyWall(self.world, -1, 0, ((0, -0.3), (1, 0.7), (1, 7.3), (0, 8.3))) #right PolyWall(self.world, 16, 0, ((0, 0.7), (1, -0.3), (1, 8.3), (0, 7.3))) Pocket(self.world, -0.3, -0.3) Pocket(self.world, 8, -0.5) Pocket(self.world, 16.4, -0.3) Pocket(self.world, -0.3, 8.4) Pocket(self.world, 8, 8.5) Pocket(self.world, 16.4, 8.4) Ball.shadow_image = pygame.image.load("ball-shadow.png").convert_alpha() Ball.shading_image = pygame.image.load("ball-shading.png").convert_alpha() Ball(self.world, 1, 10, 4) Ball(self.world, 2, 10.5, 4.3) Ball(self.world, 3, 10.5, 3.7) Ball(self.world, 4, 11, 4.6) Ball(self.world, 9, 11, 4) Ball(self.world, 5, 11, 3.4) Ball(self.world, 6, 11.5, 4.3) Ball(self.world, 7, 11.5, 3.7) Ball(self.world, 8, 12, 4) self.cue = Ball(self.world, 0, 4, 4) self.ready = True
def initilize(self): # Define the size of the world. Simulation will still work # if bodies reach the end of the world, but it will be slower. worldAABB = Box2D.b2AABB() worldAABB.lowerBound.Set(-100, -100) worldAABB.upperBound.Set(100, 100) # Define the gravity vector. gravity = Box2D.b2Vec2(0, -10) # Do we want to let bodies sleep? doSleep = True # Construct a world object, which will hold and simulate the rigid bodies. Manager.world = Box2D.b2World(worldAABB, gravity, doSleep) self.counter = 0 self.update_time = 1000.0/60 # 16.666
def __init__(self,parent): self.contact_listener = MyContactListener() self.contact_listener.physics = self self.contact_filter = MyContactFilter() self.contact_filter.physics = self self.parent = parent self.worldAABB=box2d.b2AABB() self.worldAABB.lowerBound = (-100,-globals.screen.y-100) self.worldAABB.upperBound = (100 + self.parent.absolute.size.x*self.scale_factor,100 + self.parent.absolute.size.y*self.scale_factor + 100) self.gravity = (0, 0) self.doSleep = True self.world = box2d.b2World(self.worldAABB, self.gravity, self.doSleep) self.world.SetContactListener(self.contact_listener) self.world.SetContactFilter(self.contact_filter) self.timeStep = 1.0 / 60.0 self.velocityIterations = 10 self.positionIterations = 8 self.max_zoom = 2.0 self.objects = []
def __init__(self, dimensions=((0,0),(100,100)), \ gravity=(0,0), \ velocityIterations=20, \ positionIterations=20, \ timeStep=1.0/60): # set up box2D worldAABB = box2d.b2AABB() lower, upper = dimensions worldAABB.lowerBound.Set(*lower) worldAABB.upperBound.Set(*upper) self.world = box2d.b2World(worldAABB, gravity, True) #doSleep=True self.dimensions = dimensions self.gravity = gravity self.velocityIterations = velocityIterations self.positionIterations = positionIterations self.timeStep = timeStep self.contactListener = ContactListener() self.world.SetContactListener(self.contactListener)
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) # Set Boundaries self.worldAABB = box2d.b2AABB() self.worldAABB.lowerBound = (-100.0, -100.0) self.worldAABB.upperBound = (100.0, 100.0) # Gravity + Bodies will sleep on outside self.gravity = gravity self.doSleep = True # Create the World self.world = box2d.b2World(self.worldAABB, self.gravity, self.doSleep) # Init Colors self.init_colors() # Set Pixels per Meter self.ppm = ppm
def MouseDown(self, p): self.mouseWorld = p self.mouseTracing = True self.mouseTracerPosition = p self.mouseTracerVelocity = Box2D.b2Vec2(0.0, 0.0) if self.mouseJoint: return aabb = Box2D.b2AABB(lowerBound=p - (0.001, 0.001), upperBound=p + (0.001, 0.001)) query = QueryCallback(p) self.world.QueryAABB(query, aabb) if query.fixture: body = query.fixture.body self.mouseJoint = self.world.CreateMouseJoint( bodyA=self.ground, bodyB=body, target=p, maxForce=100.0 * body.mass) body.awake = True
def MouseDown(self, p): """ Indicates that there was a left click at point p (world coordinates) """ if self.mouseJoint != None: return # Create a mouse joint on the selected body (assuming it's dynamic) # Make a small box. aabb = box2d.b2AABB() aabb.lowerBound = p - (0.001, 0.001) aabb.upperBound = p + (0.001, 0.001) # Query the world for overlapping shapes. body = None k_maxCount = 10 # maximum amount of shapes to return (count, shapes) = self.world.Query(aabb, k_maxCount) for shape in shapes: shapeBody = shape.GetBody() if not shapeBody.IsStatic() and shapeBody.GetMass() > 0.0: if shape.TestPoint(shapeBody.GetXForm(), p): # is it inside? body = shapeBody break if body: # A body was selected, create the mouse joint md = box2d.b2MouseJointDef() md.body1 = self.world.GetGroundBody() md.body2 = body md.target = p md.maxForce = 1000.0 * body.GetMass() self.mouseJoint = self.world.CreateJoint(md).getAsType() body.WakeUp()
#!/usr/bin/python2.6
def runsim(GD, locs, seed, mapgen, vel, frames, slowmo=1): random.seed(seed) # Define the size of the world. Simulation will still work # if bodies reach the end of the world, but it will be slower. worldAABB = box2d.b2AABB() worldAABB.lowerBound = (-100, -100) worldAABB.upperBound = (100, 100) # Define the gravity vector. gravity = box2d.b2Vec2(0, -10) # Do we want to let bodies sleep? doSleep = False # Construct a world object, which will hold and simulate the rigid bodies. world = box2d.b2World(gravity, doSleep) if 1: sd = box2d.b2PolygonShape() sd.SetAsBox(50.0, 10.0) bd = box2d.b2BodyDef() bd.position = (0.0, -10.05) ground = world.CreateBody(bd) groundBoxFixture = box2d.b2FixtureDef(shape=sd) ground.CreateFixture(groundBoxFixture) else: # Define the ground body. groundBodyDef = box2d.b2BodyDef() groundBodyDef.position = [0, -10] # Call the body factory which allocates memory for the ground body # from a pool and creates the ground box shape (also from a pool). # The body is also added to the world. groundBody = world.CreateBody(groundBodyDef) # Define the ground box shape. groundShapeDef = box2d.b2PolygonShape() # The extents are the half-widths of the box. groundShapeDef.SetAsBox(50, 10) # Add the ground shape to the ground body. help(groundBody) groundBody.CreateShape(groundShapeDef) bodies = [b for b in mapgen(world)] # Prepare for simulation. Typically we use a time step of 1/60 of a # second (60Hz) and 10 velocity/8 position iterations. This provides a # high quality simulation in most game scenarios. timeStep = 1.0 / 60 vel_iters, pos_iters = 10, 8 vel_iters, pos_iters = 1000, 1000 # class MyContactListener(box2d.b2ContactListener): # def __init__(self): # self.contact = False # super(MyContactListener, self).__init__() # def Add(self, point): # if box2d.b2CircleShape in (type(point.shape1), type(point.shape2)): # self.contact = True # contactListener = MyContactListener() # world.SetContactListener(contactListener) def bodxy(b): x, y = int((220 + 60 * (b.position.x + ox))), int( (270 - 60 * (b.position.y + oy))) return x - 16, y - 16 bullet = None yground = 265 time = 0.0 for f in range(800): t = min(1, f / 400.) xorg = -900 + 900 * smoothstep(t) # GD.scrollxy(xorg, 0) # COMM+0 SCROLL_X for top section # COMM+2 SCROLL_Y for top section # COMM+4 Y-coordinate of start of middle section # COMM+6 SCROLL_X for middle section # COMM+8 SCROLL_Y for middle section # COMM+10 Y-coordinate of start of bottom section # COMM+12 SCROLL_X for bottom section # COMM+14 SCROLL_Y for bottom section GD.wrstr( gd.COMM, array.array('H', [ int(xorg / 4) & 511, 0, 90, int(xorg / 2) & 511, 0, 34 * 8, int(xorg) & 511, 0 ])) world.Step(timeStep, vel_iters, pos_iters) for i, b in enumerate(bodies): (ox, oy) = (0, 0) x, y = bodxy(b) a = (f / 4) % 120 a = int(30 * b.angle / (math.pi / 2)) % 120 fr = a % 30 rot = (a / 30) % 4 tab = ([0, 1, 2, 3], [1, 3, 0, 2], [3, 2, 1, 0], [2, 0, 3, 1])[rot] for j in range(4): frame, pal = locs[4 * fr + tab[j]] GD.sprite(4 * i + j, x + (16 * (j % 2)) - xorg, y + 16 * (j / 2), frame, pal, [0, 3, 6, 5][rot]) if bullet: x, y = bodxy(bullet) GD.sprite(255, x + 8, y + 8, 63, 0) GD.sync_spr() GD.wait() time += timeStep if f == 400: GD.pause() bullet = aball(world, -4, 0, .1) bullet.mass = 9 bullet.linearVelocity = box2d.b2Vec2(8, 4) * 1