示例#1
0
    def __init__(self, x0, target, render):
        # TODO: try to pass the initial point as shift so that it will not affect the original code
        self.render = render
        if self.render:
            super(VehicleWorld, self).__init__()
        else: 
            self.world = b2.b2World(gravity=(0, -10), doSleep=True)
        self.world.gravity = (0.0, 0.0)
        self.initial_position = (x0[0], x0[1])
        self.initial_angle = x0[2]
        self.initial_linear_velocity = (x0[3], x0[4])
        self.initial_angular_velocity = x0[5]
        # ?? how to assign the parameter setting to dynamic body itself?  
        self.wheelbase = BUS_LENGTH
        self.lr = BUS_LENGTH/2

        ground = self.world.CreateBody(position=(0,0)) # set the initial position of the body
        ground.CreateEdgeChain(
            [(-GROUND_EDGE, -GROUND_EDGE),
             (-GROUND_EDGE, GROUND_EDGE),
             (GROUND_EDGE, GROUND_EDGE),
             (GROUND_EDGE, -GROUND_EDGE),
             (-GROUND_EDGE, -GROUND_EDGE)]
             )
        # ground.CreateEdgeChain(
        #     [(0, 0), (0, GROUND_EDGE), (GROUND_EDGE, GROUND_EDGE), (GROUND_EDGE, 0),(0, 0)])

        # self.introduce_roads()

        # Initialize the rectangular bus
        rectangle_fixture = b2.b2FixtureDef(
            shape=b2.b2PolygonShape(box=(BUS_LENGTH/2, BUS_WIDTH/2)),
            density=1.5,
            friction=1.,
        )
        square_fixture = b2.b2FixtureDef(
            shape=b2.b2PolygonShape(box=(0.5, 0.5)),
            density=10,
            friction=5.,
        )

        self.body = self.world.CreateDynamicBody(
            position=self.initial_position,
            angle=self.initial_angle,
            linearVelocity=self.initial_linear_velocity,
            angularVelocity=self.initial_angular_velocity,
            fixtures=rectangle_fixture,
        )

        self.target = self.world.CreateStaticBody(
            position=target[:2],
            # angle=target[2],
            # linearVelocity=target[3:5],
            # angularVelocity=target[5],
            angle=self.initial_angle,
            linearVelocity=self.initial_linear_velocity,
            angularVelocity=self.initial_angular_velocity,
            fixtures = rectangle_fixture,
        )
        self.target.active = False
示例#2
0
    def __init__(self, x0, target, render):
        self.render = render
        if self.render:
            super(CarWorld, self).__init__()
        else:
            self.world = b2.b2World(gravity=(0, 0), doSleep=True)

        self.world.gravity = (0.0, 0.0)
        self.initial_position = (x0[0], x0[1])
        self.initial_angle = 0

        ground = self.world.CreateBody(position=(0, 20))
        ground.CreateEdgeChain(
            [(-10, -30),
             (-10, 5),
             (-30, 30),]
            )
	    
        ground.CreateEdgeChain(
            [(10, -30),
             (10, 5),
             (-10, 30),]
            )
	    
        xf1 = b2.b2Transform()
        xf1.angle = 0.3524 * b2.b2_pi
        xf1.position = b2.b2Mul(xf1.R, (1.0, 0.0))

        xf2 = b2.b2Transform()
        xf2.angle = -0.3524 * b2.b2_pi
        xf2.position = b2.b2Mul(xf2.R, (-1.0, 0.0))

        self.car = TDCar(self.world, position=self.initial_position, angle=self.initial_angle)

        self.target = self.world.CreateStaticBody(
            position=target[:2],
            angle=self.initial_angle,
            shapes=[b2.b2PolygonShape(vertices=[xf1*(-1, 0), xf1*(1, 0),
                                                xf1*(0, .5)]),
                    b2.b2PolygonShape(vertices=[xf2*(-1, 0), xf2*(1, 0),
                                                xf2*(0, .5)])],
        )
        self.target.active = False


        self.start = self.world.CreateStaticBody(
            position=self.initial_position,
            angle=self.initial_angle,
            shapes=[b2.b2PolygonShape(vertices=[xf1*(-1, 0), xf1*(1, 0),
                                                xf1*(0, .5)]),
                    b2.b2PolygonShape(vertices=[xf2*(-1, 0), xf2*(1, 0),
                                                xf2*(0, .5)])],
        )
        self.start.active = False
示例#3
0
    def __init__(self, x0, target, render):
        self.render = render
        if self.render:
            super(PointMassWorld, self).__init__()
        else:
            self.world = b2.b2World(gravity=(0, -10), doSleep=True)

        x0 = np.asfarray(x0)
        target = np.asfarray(target)

        self.world.gravity = (0.0, 0.0)
        self.initial_position = (x0[0], x0[1])
        self.initial_angle = b2.b2_pi
        self.initial_linear_velocity = (x0[2], x0[3])
        self.initial_angular_velocity = 0

        ground = self.world.CreateBody(position=(0, 20))
        ground.CreateEdgeChain([(-20, -20), (-20, 20), (20, 20), (20, -20),
                                (-20, -20)])

        xf1 = b2.b2Transform()
        xf1.angle = 0.3524 * b2.b2_pi
        xf1.position = b2.b2Mul(xf1.R, (1.0, 0.0))

        xf2 = b2.b2Transform()
        xf2.angle = -0.3524 * b2.b2_pi
        xf2.position = b2.b2Mul(xf2.R, (-1.0, 0.0))
        self.body = self.world.CreateDynamicBody(
            position=self.initial_position,
            angle=self.initial_angle,
            linearVelocity=self.initial_linear_velocity,
            angularVelocity=self.initial_angular_velocity,
            angularDamping=5,
            linearDamping=0.1,
            shapes=[
                b2.b2PolygonShape(
                    vertices=[xf1 * (-1, 0), xf1 * (1, 0), xf1 * (0, .5)]),
                b2.b2PolygonShape(
                    vertices=[xf2 * (-1, 0), xf2 * (1, 0), xf2 * (0, .5)])
            ],
            shapeFixture=b2.b2FixtureDef(density=1.0),
        )
        self.target = self.world.CreateStaticBody(
            position=target[:2],
            angle=self.initial_angle,
            shapes=[
                b2.b2PolygonShape(
                    vertices=[xf1 * (-1, 0), xf1 * (1, 0), xf1 * (0, .5)]),
                b2.b2PolygonShape(
                    vertices=[xf2 * (-1, 0), xf2 * (1, 0), xf2 * (0, .5)])
            ],
        )
        self.target.active = False
示例#4
0
def createBoxFixture(pos=(0, 0),
                     width=1.0,
                     height=1.0,
                     bDynamic=True,
                     density=1,
                     collisionGroup=None,
                     restitution=None):
    global world
    boxShape = Box2D.b2PolygonShape()
    boxShape.SetAsBox(width, height, pos,
                      0)  # width, height, position (x,y), angle
    fixtureDef = Box2D.b2FixtureDef()
    fixtureDef.shape = boxShape

    fixtureDef.friction = 0.3
    if (abs(world.gravity[1]) > 1):
        fixtureDef.restitution = 0.6

    if (restitution != None): fixtureDef.restitution = restitution

    if (collisionGroup != None): fixtureDef.filter.groupIndex = collisionGroup

    if bDynamic: fixtureDef.density = density
    else: fixtureDef.density = 0
    return fixtureDef
示例#5
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)
示例#6
0
    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
示例#7
0
 def perform(self, time):
     """
     Morph line into real collideable figure.
     """
     #Define geometry and time data
     actor = self.master.owner
     v1 = actor.b2body.GetLocalPoint(pixels_to_tiles((self.start.x, self.start.y)))
     v2 = actor.b2body.GetLocalPoint(pixels_to_tiles((self.end.x, self.end.y)))
     if v2.x <= v1.x:
         v1, v2 = v2, v1
     vlen = math.sqrt((v2.x-v1.x)*(v2.x-v1.x)+(v2.y-v1.y)*(v2.y-v1.y))
     vcent = ((v1.x+v2.x)/2.0, (v1.y+v2.y)/2.0)
     vangle = math.asin((v2.y-v1.y)/vlen)
     v = self.end - self.start
     start = gm.Point2(self.start.x, self.start.y)
     self.trace = gm.LineSegment2(start, v)
     self.cshape = shape_to_cshape(self.trace)
     self.set_time_to_complete(time)
     self.b2fixture = actor.b2body.CreateFixture(b2.b2FixtureDef(shape=b2.b2PolygonShape(box=(vlen, 0,
                                                                                              vcent, vangle)),
                                                                 isSensor=True, userData=self))
     self.b2fixture.filterData.categoryBits = B2SWING
     self.b2fixture.filterData.maskBits = B2HITZONE | B2SWING | B2BODYPART
     actor.world.addEventHandler(self.b2fixture, self.on_begin_contact, self.on_end_contact)
     self.schedule(self.update)
示例#8
0
    def __init__(self, verbose=1):
        self.contactListener_keep_ref = FrictionDetector(self)
        self.world = Box2D.b2World(
            (0, 0), contactListener=self.contactListener_keep_ref)
        self.viewer = None
        self.invisible_state_window = None
        self.invisible_video_window = None
        self.road = None
        self.car = None
        self.reward = 0.0
        self.prev_reward = 0.0
        self.verbose = verbose

        self.fd_tile = Box2D.b2FixtureDef(shape=Box2D.b2PolygonShape(
            vertices=[(0, 0), (1, 0), (1, -1), (0, -1)]))

        self.state_temp = None  # Yonv1943
        self.tile_visited_count = 0
        self.road_poly = []
        self.transform = None
        self.t = None
        self.num_step = 0

        self.env_name = 'CarRacingFix'
        self.state_dim = (STATE_W, STATE_H, 3 * 2)
        self.action_dim = 6
        self.if_discrete = False
        self.max_step = 512
        self.target_return = 950
        self.action_max = 1
示例#9
0
    def __init__(self, seg_vertices=None, **kwargs):
        super().__init__(**kwargs)

        # TODO: right now this assumes that all subpolygons have the same number of edges
        # TODO: rewrite such that arbitrary subpolygons can be used here
        vertices = seg_vertices

        centroid = np.zeros(2)
        area = .0
        for vs in vertices:
            # compute centroid of circle_to_polygon
            r0 = np.roll(vs[:, 0], 1)
            r1 = np.roll(vs[:, 1], 1)
            a = 0.5 * np.abs(np.dot(vs[:, 0], r1) - np.dot(vs[:, 1], r0))
            area += a
            # FIXME This changed in refactoring. It is wrong probably.
            # Find a way to use compute_centroid(points) function
            centroid += np.mean(vs, axis=0) * a

        centroid /= area

        self.__local_vertices = vertices - centroid
        self.__local_vertices.setflags(write=False)
        for v in self.__local_vertices:
            self._body.CreatePolygonFixture(
                shape=Box2D.b2PolygonShape(vertices=v.tolist()),
                density=self.physics_pars['density'],
                friction=self.physics_pars['friction'],
                restitution=self.physics_pars['restitution'],
                # radius=.00000001
            )

        self._fixtures = self._body.fixtures
示例#10
0
    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)
示例#11
0
文件: fisica.py 项目: frandorr/pilas
    def __init__(self, x, y, puntos, dinamica=True, densidad=1.0,
            restitucion=0.56, friccion=10.5, amortiguacion=0.1,
            fisica=None, sin_rotacion=False):

        Figura.__init__(self)

        self._escala = 1

        self.puntos = puntos
        self.dinamica = dinamica
        self.fisica = fisica
        self.sin_rotacion = sin_rotacion

        if not self.fisica:
            self.fisica = pilas.escena_actual().fisica

        self.vertices = [(convertir_a_metros(x1) * self._escala, convertir_a_metros(y1) * self._escala) for (x1, y1) in self.puntos]

        fixture = box2d.b2FixtureDef(shape=box2d.b2PolygonShape(vertices=self.vertices),
                                     density=densidad,
                                     linearDamping=amortiguacion,
                                     friction=friccion,
                                     restitution=restitucion)

        self.userData = { 'id' : self.id }
        fixture.userData = self.userData

        if self.dinamica:
            self._cuerpo = self.fisica.mundo.CreateDynamicBody(position=(0, 0), fixtures=fixture)
        else:
            self._cuerpo = self.fisica.mundo.CreateKinematicBody(position=(0, 0), fixtures=fixture)

        self._cuerpo.fixedRotation = self.sin_rotacion
示例#12
0
文件: personage.py 项目: dregor/game
    def __init__(self, game, position=(0, 0), angle=0, additive=(0, 0), name='', speed=100, is_inside=True,
                 is_you=False, body=None, orientation=0):
        Composite.__init__(self, game=game, position=position, angle=angle, is_inside=is_inside, body=body)
        self.is_you = is_you
        self.name = name
        self.speed = speed
        self.additive = additive
        self.orientation = orientation

        for fixture in self.body.body.fixtures:
            fixture.filterData.maskBits = Bits.PERSONAGE_MASK
            fixture.filterData.categoryBits = Bits.PERSONAGE_BITS

        if self.is_you:
            self.center_box = self.game.world.CreateDynamicBody(position=self.get_position(),
                                                                shapes=B2.b2PolygonShape(box=(0.5, 0.5)))
            for item in self.center_box.fixtures:
                item.filterData.maskBits = Bits.NOTHING_MASK
                item.filterData.categoryBits = Bits.NOTHING_BITS

            self.game.world.CreatePrismaticJoint(bodyA=self.game.maw.center_box,
                                                 bodyB=self.center_box,
                                                 axis=(0, -1))

            self.game.world.CreateRevoluteJoint(bodyA=self.center_box,
                                                bodyB=self.body.body)
示例#13
0
    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
示例#14
0
    def __init__(self, world, ID, body_position, heading=0):
        self.ID = ID
        self.body = world.CreateDynamicBody(position=body_position)
        ps = b2.b2PolygonShape()
        ps.SetAsBox(self.width/2, self.height/2)
        ps1 = b2.b2PolygonShape()
        ps1.SetAsBox(self.grabber_width/2, self.grabber_height/2,
                     b2.b2Vec2((-self.width/2 - self.grabber_width/2),
                               (self.height/2 - self.grabber_height/2)),0)
        ps2 = b2.b2PolygonShape()
        ps2.SetAsBox(self.grabber_width/2, self.grabber_height/2,
                     b2.b2Vec2((-self.width/2 - self.grabber_width/2),
                               (self.grabber_height/2 - self.height/2)),0)

        self.body.CreateFixture(shape=ps, density=self.density)
        self.body.CreateFixture(shape=ps1, density=self.grabber_density)
        self.body.CreateFixture(shape=ps2, density=self.grabber_density)
示例#15
0
    def __init__(self, x0, target):
        super(PointMassWorld, self).__init__()
        self.world.gravity = (0.0, 0.0)
        self.initial_position = (x0[0], x0[1])
        self.initial_angle = b2.b2_pi
        self.initial_linear_velocity = (x0[2], x0[3])
        self.initial_angular_velocity = 0

        ground = self.world.CreateBody(position=(0, 20))
        ground.CreateEdgeChain(
            [(-20, -20),
             (-20, 20),
             (20, 20),
             (20, -20),
             (-20, -20)]
            )

        xf1 = b2.b2Transform()
        xf1.angle = 0.3524 * b2.b2_pi
        xf1.position = b2.b2Mul(xf1.R, (1.0, 0.0))

        xf2 = b2.b2Transform()
        xf2.angle = -0.3524 * b2.b2_pi
        xf2.position = b2.b2Mul(xf2.R, (-1.0, 0.0))
        self.body = self.world.CreateDynamicBody(
            position=self.initial_position,
            angle=self.initial_angle,
            linearVelocity=self.initial_linear_velocity,
            angularVelocity=self.initial_angular_velocity,
            angularDamping=5,
            linearDamping=0.1,
            shapes=[b2.b2PolygonShape(vertices=[xf1*(-1, 0),
                                                xf1*(1, 0), xf1*(0, .5)]),
                    b2.b2PolygonShape(vertices=[xf2*(-1, 0),
                                                xf2*(1, 0), xf2*(0, .5)])],
            shapeFixture=b2.b2FixtureDef(density=1.0),
        )
        self.target = self.world.CreateStaticBody(
            position=target,
            angle=self.initial_angle,
            shapes=[b2.b2PolygonShape(vertices=[xf1*(-1, 0), xf1*(1, 0),
                                                xf1*(0, .5)]),
                    b2.b2PolygonShape(vertices=[xf2*(-1, 0), xf2*(1, 0),
                                                xf2*(0, .5)])],
        )
        self.target.active = False
示例#16
0
 def setup_b2body(self):
     super(Hit_Zone, self).setup_b2body()
     cshape = self.cshape
     hit_shape = self.hit_shape
     img = self.image
     if hit_shape is RECTANGLE:
         rx, ry = pixels_to_tiles((cshape.rx, cshape.ry))
         self.b2body.CreateFixture(b2.b2FixtureDef(shape=b2.b2PolygonShape(box=(rx, ry)), isSensor=True,
                                                   userData=self))
     elif hit_shape is LINE:
         r = pixels_to_tiles(img.width/2.0)
         self.b2body.CreateFixture(b2.b2FixtureDef(shape=b2.b2PolygonShape(box=(r, 0)),
                                                   isSensor=True, userData=self))
     self.b2body.gravityScale = 0
     self.b2body.fixtures[-1].filterData.categoryBits = B2HITZONE
     self.b2body.fixtures[-1].filterData.maskBits = B2HITZONE | \
                                                    B2SWING | B2LEVEL | B2BODYPART
     self.world.addEventHandler(self.b2body.fixtures[-1], self.on_begin_contact, self.on_end_contact)
示例#17
0
文件: rectangulo.py 项目: DrDub/pilas
    def __init__(self, fisica, pilas, x, y, ancho, alto, dinamica=True,
                 densidad=1.0, restitucion=0.56, friccion=10.5,
                 amortiguacion=0.1, sin_rotacion=False, sensor=False,
                 plataforma=False):

        Figura.__init__(self, fisica, pilas)

        x = utils.convertir_a_metros(x)
        y = utils.convertir_a_metros(y)

        self._ancho = utils.convertir_a_metros(ancho)
        self._alto = utils.convertir_a_metros(alto)
        self._escala = 1

        self.fisica = fisica

        if not self.fisica:
            self.fisica = pilas.escena_actual().fisica

        if not dinamica:
            densidad = 0

        shape = box2d.b2PolygonShape(box=(self._ancho/2, self._alto/2))
        shape.SetAsBox(self._ancho/2.0, self._alto/2.0)

        try:
            fixture = box2d.b2FixtureDef(
                                     shape=shape,
                                     density=densidad,
                                     friction=friccion,
                                     restitution=restitucion)
        except TypeError:
            fixture = box2d.b2FixtureDef(
                                     shape=shape,
                                     density=densidad,
                                     linearDamping=amortiguacion,
                                     friction=friccion,
                                     restitution=restitucion)
            
        # Agregamos un identificador para controlarlo posteriormente en
        # las colisiones.
        self.userData = {'id': self.id, 'figura': self}
        fixture.userData = self.userData

        if plataforma:
            self._cuerpo = self.fisica.mundo.CreateStaticBody(position=(x, y), fixtures=fixture)
            self.dinamica = False
        else:
            self._cuerpo = self.fisica.mundo.CreateDynamicBody(position=(x, y), fixtures=fixture)
            self.dinamica = dinamica

        self.sin_rotacion = sin_rotacion
        self.sensor = sensor

        if not dinamica:
            self._cuerpo.mass = 1000000
示例#18
0
文件: map.py 项目: polmuz/spacecraft
 def create_body(self, _x, _y):
     self.x = float(self.node.attrib["x"])
     self.y = float(self.node.attrib["y"])
     self.width = float(self.node.attrib["width"])
     self.height = float(self.node.attrib["height"])
     self.body = self.map.world.CreateStaticBody(
         position=(self.x + self.width / 2, self.y + self.height / 2),
         shapes=Box2D.b2PolygonShape(box=(self.width / 2, self.height / 2)),
         userData=self,
     )
示例#19
0
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
示例#20
0
 def b2drop(self):
     self.cshape.center = eu.Vector2(self.position[0], self.position[1])
     rx, ry = pixels_to_tiles((self.cshape.rx, self.cshape.ry))
     self.b2body.CreateFixture(b2.b2FixtureDef(shape=b2.b2PolygonShape(box=(rx, ry)), userData=self))
     self.b2body.fixtures[-1].filterData.categoryBits = B2ITEM
     self.b2body.fixtures[-1].filterData.maskBits = B2LEVEL
     self.b2body.fixtures[-1].friction = 10
     x, y = pixels_to_tiles((self.cshape.center.x, self.cshape.center.y))
     self.b2body.position = (x, y)
     self.b2body.linearVelocity.x = self.master.b2body.linearVelocity.x + pixels_to_tiles(randint(-500, 500))
     self.b2body.linearVelocity.y = self.master.b2body.linearVelocity.y + pixels_to_tiles(randint(-100, 100))
示例#21
0
    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()
示例#22
0
    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()
示例#23
0
    def __init__(self,
                 fisica,
                 pilas,
                 x,
                 y,
                 ancho,
                 alto,
                 dinamica=True,
                 densidad=1.0,
                 restitucion=0.5,
                 friccion=.2,
                 amortiguacion=0.1,
                 sin_rotacion=False):

        Figura.__init__(self, fisica, pilas)

        x = utils.convertir_a_metros(x)
        y = utils.convertir_a_metros(y)
        self._ancho = utils.convertir_a_metros(ancho)
        self._alto = utils.convertir_a_metros(alto)
        self._escala = 1

        self.dinamica = dinamica
        self.fisica = fisica
        self.sin_rotacion = sin_rotacion

        if not self.fisica:
            self.fisica = pilas.escena_actual().fisica

        if not self.dinamica:
            densidad = 0

        fixture = box2d.b2FixtureDef(
            shape=box2d.b2PolygonShape(box=(self._ancho / 2, self._alto / 2)),
            density=densidad,
            linearDamping=amortiguacion,
            friction=friccion,
            restitution=restitucion)

        # Agregamos un identificador para controlarlo posteriormente en las
        # colisiones.
        self.userData = {'id': self.id}
        fixture.userData = self.userData

        if self.dinamica:
            self._cuerpo = self.fisica.mundo.CreateDynamicBody(
                position=(x, y), fixtures=fixture)
        else:
            self._cuerpo = self.fisica.mundo.CreateKinematicBody(
                position=(x, y), fixtures=fixture)

        self._cuerpo.fixedRotation = self.sin_rotacion
示例#24
0
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
示例#25
0
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
示例#26
0
 def __init__(self, level):
     self.jump = False
     self.jump_sound = pygame.mixer.Sound(
         link_file('jump.wav', DATA_FILE))
     self.moving_left = False
     self.moving_right = False
     self.animations_right = [
         load_image('walk1.png', DATA_FILE, -1),  # add animations
         load_image('walk2.png', DATA_FILE, -1),
         load_image('walk3.png', DATA_FILE, -1),
         load_image('walk2.png', DATA_FILE, -1),
         load_image('walk1.png', DATA_FILE, -1),
         load_image('walk2.png', DATA_FILE, -1),
         load_image('walk3.png', DATA_FILE, -1),
         load_image('walk2.png', DATA_FILE, -1),
         load_image('walk1.png', DATA_FILE, -1),
         load_image('walk2.png', DATA_FILE, -1),
         load_image('walk3.png', DATA_FILE, -1),
         load_image('walk2.png', DATA_FILE, -1)
     ]
     self.animations_left = [
         load_image('walk-1.png', DATA_FILE, -1),
         load_image('walk-2.png', DATA_FILE, -1),
         load_image('walk-3.png', DATA_FILE, -1),
         load_image('walk-2.png', DATA_FILE, -1),
         load_image('walk-1.png', DATA_FILE, -1),
         load_image('walk-2.png', DATA_FILE, -1),
         load_image('walk-3.png', DATA_FILE, -1),
         load_image('walk-2.png', DATA_FILE, -1),
         load_image('walk-1.png', DATA_FILE, -1),
         load_image('walk-2.png', DATA_FILE, -1),
         load_image('walk-3.png', DATA_FILE, -1),
         load_image('walk-2.png', DATA_FILE, -1)
     ]
     self.sprite = load_image('stand1.png', DATA_FILE, -1)
     self.start_pos = (10, HEIGHT - self.sprite.get_height() - 48)
     self.player_location = [self.start_pos[0], self.start_pos[1]]
     self.body = level.CreateDynamicBody(  # box2d collision create
         angle=0,
         position=(self.get_box2d_coordinates()),
         shapes=b.b2PolygonShape(
             box=(self.get_box2d_size())))  # 1 = 20 pixel
     self.start_box2d = self.get_box2d_coordinates()
     self.x, self.y = 0, 0
     self.check_jump = 0
     self.anim_count = 0
     self.stand = True
     self.dir = 1  # 1 right. -1 left
     self.run = False
     self.j_check = False
     self.start = True
示例#27
0
文件: maw.py 项目: dregor/game
 def recreate(self, radius, n):
     self.radius = radius
     if n < 3:
         n = 3
     self.n = n
     for f in self.body.fixtures:
         self.body.DestroyFixture(f)
     for vertices in self._polyhedron_full(r=radius, n=n):
         fixture = B2.b2FixtureDef(
             shape=B2.b2PolygonShape(vertices=vertices),
             density=50,
             friction=5,
         )
         self.body.CreateFixture(fixture)
示例#28
0
 def addSensor(self, world, cfg):
     sensorFov = b2.b2PolygonShape()
     # Define sensor shape
     w, h = cfg.fov.width, cfg.fov.height
     self.fov = (w,h)
     fov = np.array([(-0.5*w,-0.5*h),(0.5*w,-0.5*h),
                     (0.5*w,0.5*h),(-0.5*w, 0.5*h)])
     # Move sensor relative to the body
     relpos = np.array([cfg.relpos.x, cfg.relpos.y])
     sensorFov.vertices = (fov+relpos).tolist()
     sensorFixtureDef = b2.b2FixtureDef()
     sensorFixtureDef.isSensor = True
     sensorFixtureDef.shape = sensorFov
     self.sensor = self.body.CreateFixture(sensorFixtureDef)
示例#29
0
    def _create_table(self):
        """
    Creates the walls of the table
    :return:
    """
        ## Walls in world RF
        left_wall_body = self.world.CreateStaticBody(
            position=(0, self.params.TABLE_CENTER[1]),
            userData={'name': 'left wall'},
            shapes=b2.b2PolygonShape(box=(self.params.WALL_THICKNESS / 2,
                                          self.params.TABLE_SIZE[1] / 2)))

        right_wall_body = self.world.CreateStaticBody(
            position=(self.params.TABLE_SIZE[0], self.params.TABLE_CENTER[1]),
            userData={'name': 'right wall'},
            shapes=b2.b2PolygonShape(box=(self.params.WALL_THICKNESS / 2,
                                          self.params.TABLE_SIZE[1] / 2)))

        upper_wall_body = self.world.CreateStaticBody(
            position=(self.params.TABLE_CENTER[0], self.params.TABLE_SIZE[1]),
            userData={'name': 'upper wall'},
            shapes=b2.b2PolygonShape(box=(self.params.TABLE_SIZE[0] / 2,
                                          self.params.WALL_THICKNESS / 2)))
        bottom_wall_body = self.world.CreateStaticBody(
            position=(self.params.TABLE_CENTER[0], 0),
            userData={'name': 'bottom wall'},
            shapes=b2.b2PolygonShape(box=(self.params.TABLE_SIZE[0] / 2,
                                          self.params.WALL_THICKNESS / 2)))

        self.walls = [
            left_wall_body, upper_wall_body, right_wall_body, bottom_wall_body
        ]

        ## world RF -> table RF
        self.wt_transform = -self.params.TABLE_CENTER
        ## table RF -> world RF
        self.tw_transform = self.params.TABLE_CENTER
示例#30
0
    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
示例#31
0
 def createBody(self, b2world, w, h):
     bodyDef = Box2D.b2BodyDef()
     bodyDef.type = Box2D.b2_dynamicBody
     bodyDef.fixedRotation = True
     bodyDef.position = (Settings.B2SCALE * self.rect.left, Settings.B2SCALE * self.rect.top)
     bodyDef.bullet = True
     bodyDef.linearDamping = 6.0
     self.body = b2world.CreateBody(bodyDef)
     w /= 2
     h /= 2
     poly = Box2D.b2PolygonShape( box=(Settings.B2SCALE*w, Settings.B2SCALE*h, (Settings.B2SCALE*w,Settings.B2SCALE*h), 0) )
     
     self.body.CreateFixture(shape=poly, density=1, friction=0)
     return self.body
     
示例#32
0
    def __init__(self, fisica, pilas, x, y, ancho, alto, dinamica=True,
                 densidad=1.0, restitucion=0.56, friccion=10.5,
                 amortiguacion=0.1, sin_rotacion=False, sensor=False,
                 plataforma=False):

        Figura.__init__(self, fisica, pilas)

        x = utils.convertir_a_metros(x)
        y = utils.convertir_a_metros(y)

        self._ancho = utils.convertir_a_metros(ancho)
        self._alto = utils.convertir_a_metros(alto)
        self._escala = 1

        self.fisica = fisica

        if not self.fisica:
            self.fisica = pilas.escena_actual().fisica

        if not dinamica:
            densidad = 0

        shape = box2d.b2PolygonShape(box=(self._ancho/2, self._alto/2))
        shape.SetAsBox(self._ancho/2.0, self._alto/2.0)
        fixture = box2d.b2FixtureDef(shape=shape,
                                     density=densidad,
                                     linearDamping=amortiguacion,
                                     friction=friccion,
                                     restitution=restitucion)

        # Agregamos un identificador para controlarlo posteriormente en
        # las colisiones.
        self.userData = {'id': self.id, 'figura': self}
        fixture.userData = self.userData

        if plataforma:
            self._cuerpo = self.fisica.mundo.CreateStaticBody(position=(x, y), fixtures=fixture)
            self.dinamica = False
        else:
            self._cuerpo = self.fisica.mundo.CreateDynamicBody(position=(x, y), fixtures=fixture)
            self.dinamica = dinamica

        self.sin_rotacion = sin_rotacion
        self.sensor = sensor

        if not dinamica:
            self._cuerpo.mass = 1000000
示例#33
0
def create_dynamic_polygon(vertices, world):
    body = world.CreateDynamicBody()

    # box2d cannot create polygons with 16 or more vertices so triangulate them
    if len(vertices) >= 16:
        fixtures = triangulate(vertices, body)
        return body, fixtures

    box = Box2D.b2PolygonShape(vertices=vertices)

    # this means we have a concave shape
    if len(box.vertices) < len(vertices) - 1:
        fixtures = triangulate(vertices, body)
        return body, fixtures

    box = body.CreatePolygonFixture(vertices=vertices, density=1, friction=.1, restitution=.5)
    return body, [box]
示例#34
0
文件: composite.py 项目: dregor/game
 def __init__(self, game, position=(0, 0), angle=0, is_inside=True, name='', body=None):
     self.name = name
     self._is_inside = is_inside
     self.game = game
     self.parts = []
     self.joints = []
     self.old_angle = angle
     if body:
         self.body = body
     else:
         self.body = self.game.world.CreateDynamicBody(
             position=position,
             shapes=B2.b2PolygonShape(box=(0.5, 0.5)))
         for item in self.body.fixtures:
             item.filterData.maskBits = Bits.NOTHING_MASK
             item.filterData.categoryBits = Bits.NOTHING_BITS
     self.add_part(self.body)
示例#35
0
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
示例#36
0
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
示例#37
0
文件: fisica.py 项目: frandorr/pilas
    def __crear_fixture(self):
        fixture = box2d.b2FixtureDef(shape=box2d.b2PolygonShape(box=(self._ancho/2, self._alto/2)),
                                     density=self._cuerpo.fixtures[0].density,
                                     linearDamping=self._cuerpo.fixtures[0].body.linearDamping,
                                     friction=self._cuerpo.fixtures[0].friction,
                                     restitution=self._cuerpo.fixtures[0].restitution)

        fixture.userData = self.userData

        self.fisica.mundo.DestroyBody(self._cuerpo)

        if self.dinamica:
            self._cuerpo = self.fisica.mundo.CreateDynamicBody(position=(self._cuerpo.position.x, self._cuerpo.position.y), angle=self._cuerpo.angle, linearVelocity=self._cuerpo.linearVelocity, fixtures=fixture)    
        else:
            self._cuerpo = self.fisica.mundo.CreateKinematicBody(position=(self._cuerpo.position.x, self._cuerpo.position.y), angle=self._cuerpo.angle, fixtures=fixture)

        self._cuerpo.fixedRotation = self.sin_rotacion
示例#38
0
文件: maw.py 项目: dregor/game
    def __init__(self, game, position=(0, 0), angle=0, radius=10, n=3):
        GameObject.__init__(self, game, position, angle, image='images/default.png')
        self.center_box = self.game.world.CreateStaticBody(
            position=position,
            shapes=B2.b2PolygonShape(box=(0.5, 0.5))
        )
        for item in self.center_box.fixtures:
            item.filterData.maskBits = Bits.NOTHING_MASK
            item.filterData.categoryBits = Bits.NOTHING_BITS

        self.game.world.CreateRevoluteJoint(bodyA=self.body,
                                            bodyB=self.center_box,
                                            anchor=position)
        self.recreate(radius, n)
        for item in self.body.fixtures:
            item.filterData.maskBits = Bits.FULL_MASK
            item.filterData.categoryBits = Bits.FULL_BITS
示例#39
0
def createGround(position=[0,-20], bMatplotlib = True):
    global world, fig, ax
    groundBodyDef = Box2D.b2BodyDef()
    groundBodyDef.position = Box2D.b2Vec2(0,-20)   
    groundBody = world.CreateBody(groundBodyDef)

    groundBox = Box2D.b2PolygonShape()
    groundBox.SetAsBox(100, 10)
    fixture = groundBody.CreateFixturesFromShapes(groundBox)
    
    if(bMatplotlib):
        createGlobalFigure()
        shape = fixture.shape
        vertices=[groundBody.transform*v for v in shape.vertices]
        poly = plt.Polygon(vertices, lw=5, edgecolor='b')
        ax.add_patch( poly )

    return groundBody
示例#40
0
def createBoxFixture(body, pos = (0,0), width=1.0, height=1.0, dynamic=True, collisionGroup = None, restitution=None):
    global world
    boxShape = Box2D.b2PolygonShape()
    boxShape.SetAsBox(width, height, pos, 0)    # width, height, position (x,y), angle 
    fixtureDef = Box2D.b2FixtureDef()
    fixtureDef.shape = boxShape

    fixtureDef.friction = 0.3
    if(abs(world.gravity[1]) > 1):
        fixtureDef.restitution = 0.6

    if(restitution != None): fixtureDef.restitution = restitution

    if(collisionGroup!=None): fixtureDef.filter.groupIndex = collisionGroup
    
    if dynamic: fixtureDef.density = 1
    else:       fixtureDef.density = 0            
    return fixtureDef
示例#41
0
    def __init__(self, pos, world, tile, width, height, tilew=1, tileh=1 ):
        self.rect = pygame.Rect(pos, (width, height)) # HUOM: width ja height tileissa
        
        self.tilew = tilew
        self.tileh = tileh
        self.world = world
        self.image = world.tileset.getTile(tile, tilew, tileh)
        
        w = width * TILESIZE * B2SCALE * 0.5
        h = height * TILESIZE * B2SCALE * 0.5
        
        bodyDef = Box2D.b2BodyDef()
        bodyDef.type = Box2D.b2_staticBody
        bodyDef.position = (B2SCALE * self.rect.left, B2SCALE * self.rect.top)
        self.body = world.b2World.CreateBody(bodyDef)

        bshape = Box2D.b2PolygonShape( box=(w, h, (w, h), 0) )
        self.body.CreateFixture(shape=bshape, density=1)
示例#42
0
 def setup_b2body(self):
     super(Actor, self).setup_b2body()
     pix_to_tile = pixels_to_tiles
     rx, ry = pix_to_tile((self.cshape.rx, self.cshape.ry))
     self.b2body.CreateFixture(
         b2.b2FixtureDef(
             shape=b2.b2PolygonShape(
                 vertices=[(-rx, ry), (-rx, -ry + 0.1), (-rx + 0.1, -ry), (rx - 0.1, -ry), (rx, -ry + 0.1), (rx, ry)]
             )
         )
     )
     self.b2body.fixtures[-1].filterData.categoryBits = B2SMTH | B2ACTOR
     self.b2body.CreateFixture(
         b2.b2FixtureDef(shape=b2.b2EdgeShape(vertex1=(-rx, -ry), vertex2=(rx, -ry)), isSensor=True)
     )
     self.b2body.fixtures[-1].filterData.categoryBits = B2GNDSENS
     self.b2body.fixtures[-1].filterData.maskBits = B2LEVEL | B2ACTOR
     self.world.addEventHandler(self.b2body.fixtures[-1], self.on_ground_begin, self.on_ground_end)
示例#43
0
文件: robot2d.py 项目: gehring/rossim
    def attachRobotBody(self, world, **kargs):
        robotBody = world.CreateDynamicBody(**kargs)
        robotBody.CreateFixture( shape = Box2D.b2CircleShape(pos=(0, 0),
                    radius = self.radius), density = 1.0, **kargs)

        for i, angle in enumerate(numpy.linspace(0, math.pi*2, self.nbumpers+1)[:-1]):
            c = numpy.array((self.radius * math.sin(angle),
                              self.radius * math.cos(angle)))
            robotBody.CreateFixture(shape = Box2D.b2PolygonShape(
                                                        box = (self.bumper_w/2,
                                                               self.bumper_h/2,
                                                        (c[0], c[1]),
                                                        angle)),
                                    density = 0.01,
                                    isSensor = True,
                                    userData = 'b'+ str(i))
        self.robotBody = robotBody
        return robotBody
示例#44
0
    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)
示例#45
0
    def _create_b2_tile_map(self, rect_map):

        def try_create_and_append_block(cells_in_block, mode):
            if cells_in_block and mode == 0:
                cells_in_block.pop()
            if cells_in_block:
                height = len(cells_in_block) if not mode else 1
                width = len(cells_in_block) if mode else 1
                half_height = height/2.0
                half_width = width/2.0
                lowest_cell = cells_in_block[0]
                cx = lowest_cell.i + half_width
                cy = lowest_cell.j + half_height
                shape.SetAsBox(half_width, half_height, (cx, cy), NO_ROTATION)
                self.b2level.CreateFixture(shape=shape, userData=cell)
                self.b2level.fixtures[-1].filterData.categoryBits = B2SMTH | B2LEVEL
                self.b2level.fixtures[-1].filterData.maskBits = B2EVERY

        cells = rect_map.cells
        m = len(cells)
        n = len(cells[0])

        shape = b2.b2PolygonShape()
        for cell_column in cells:
            cells_in_vertical_block = []
            for cell in cell_column:
                if cell.get('top'):
                    cells_in_vertical_block.append(cell)
                else:
                    try_create_and_append_block(cells_in_vertical_block, 0)
                    cells_in_vertical_block = []
            try_create_and_append_block(cells_in_vertical_block, 0)

        for j in xrange(n):
            cells_in_horizontal_block = []
            for i in xrange(m):
                cell = cells[i][j]
                if cell.get('top'):
                    cells_in_horizontal_block.append(cell)
                else:
                    try_create_and_append_block(cells_in_horizontal_block, 1)
                    cells_in_horizontal_block = []
            try_create_and_append_block(cells_in_horizontal_block, 1)
示例#46
0
 def rescale_shape(self):
     scale = self.object.scale
     bs = self._basic_shape
     if scale != self._old_scale:
         self._old_scale = scale
         if isinstance(bs, B2D.b2PolygonShape):
             vertices = []
             c = bs.centroid
             for v in bs.vertices:
                 dv = c-B2D.b2Vec2(*v)
                 dv.x *= scale[0]
                 dv.y *= scale[1]
                 vertices.append((c+dv).tuple)
             self.rescaled_shape = B2D.b2PolygonShape(vertices=vertices)
         else:
             c_scale = max(scale[0], scale[1])
             self.rescaled_shape = B2D.b2CircleShape(pos=bs.pos,
                                                   radius=c_scale*bs.radius)
     return self.rescaled_shape
示例#47
0
文件: fisica.py 项目: frandorr/pilas
    def definir_escala(self, escala):
        self._escala = escala
        self.vertices = [(convertir_a_metros(x1) * self._escala, convertir_a_metros(y1) * self._escala) for (x1, y1) in self.puntos]
        fixture = box2d.b2FixtureDef(shape=box2d.b2PolygonShape(vertices=self.vertices),
                                     density=self._cuerpo.fixtures[0].density,
                                     linearDamping=self._cuerpo.fixtures[0].body.linearDamping,
                                     friction=self._cuerpo.fixtures[0].friction,
                                     restitution=self._cuerpo.fixtures[0].restitution)

        fixture.userData = self.userData

        self.fisica.mundo.DestroyBody(self._cuerpo)

        if self.dinamica:
            self._cuerpo = self.fisica.mundo.CreateDynamicBody(position=(self._cuerpo.position.x, self._cuerpo.position.y), angle=self._cuerpo.angle, linearVelocity=self._cuerpo.linearVelocity, fixtures=fixture)    
        else:
            self._cuerpo = self.fisica.mundo.CreateKinematicBody(position=(self._cuerpo.position.x, self._cuerpo.position.y), angle=self._cuerpo.angle, fixtures=fixture)
        
        self._cuerpo.fixedRotation = self.sin_rotacion
示例#48
0
    def attachRobotBody(self, world, **kargs):
        robotBody = world.CreateDynamicBody(**kargs)
        robotBody.CreateFixture(shape=Box2D.b2CircleShape(pos=(0, 0),
                                                          radius=self.radius),
                                density=1.0,
                                **kargs)

        for i, angle in enumerate(
                numpy.linspace(0, math.pi * 2, self.nbumpers + 1)[:-1]):
            c = numpy.array(
                (self.radius * math.sin(angle), self.radius * math.cos(angle)))
            robotBody.CreateFixture(
                shape=Box2D.b2PolygonShape(box=(self.bumper_w / 2,
                                                self.bumper_h / 2,
                                                (c[0], c[1]), angle)),
                density=0.01,
                isSensor=True,
                userData='b' + str(i))
        self.robotBody = robotBody
        return robotBody
示例#49
0
def createTri(position, r=0.3, dynamic=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
    bodyDef.linearDamping = 70
    bodyDef.angularDamping = 50
    body = world.CreateBody(bodyDef)
    v = [(-r,-r),(0,r),(r,-r)]
    fixture = body.CreateFixture(shape=Box2D.b2PolygonShape(vertices=v), density=1.0, friction=0.3)
    body.userData = {"name":"tri"}

    return body
示例#50
0
def add_asteroid_play_space(world: Box2D.b2World, left_border: float,
                            right_border: float, bottom_border: float,
                            top_border: float):
    fixture_shape = Box2D.b2PolygonShape()
    width = right_border - left_border + PLAYSPACE_PADDING
    height = top_border - bottom_border + PLAYSPACE_PADDING
    fixture_shape.SetAsBox(
        width, height,
        Box2D.b2Vec2(left_border + width / 2, bottom_border + height / 2), 0)

    fixture_def = Box2D.b2FixtureDef()
    fixture_def.shape = fixture_shape
    fixture_def.isSensor = True

    play_space_body_def = Box2D.b2BodyDef()
    play_space_body_def.fixtures = [fixture_def]
    play_space_body_def.type = Box2D.b2_staticBody
    play_space_body_def.position = (0, 0)

    return world.CreateBody(play_space_body_def)
示例#51
0
    def introduce_roads():
        # Introduce traffic map 
        self.traffic = Traffic()
        self.map_scale = OBS_SCALE   # map px per meters. set it to OBS_SCALE so no resizing necessary when getting observation

        contours = self.loadMap()
        num_contour = len(contours)
        print("num", num_contour)
        obstacles = []

        for contour in contours:
            vertices = []
            for item in contour:
                new_vec = b2.b2Vec2(float(item[0][0]/BOX_SCALE), float(item[0][1]/BOX_SCALE))
                vertices.append(new_vec)
            print("vertices")
            print(vertices)
            contour_shape = b2.b2PolygonShape(vertices=vertices)
            obstacle = self.world.CreateStaticBody(position=(0,0), shapes=contour_shape)
            obstacles.append(obstacle)
示例#52
0
    def __init__(self, width: float, height: float, **kwargs):
        super().__init__(**kwargs)

        self._width = width
        self._height = height

        # TODO: right now this assumes that all subpolygons have the same number of edges
        # TODO: rewrite such that arbitrary subpolygons can be used here
        vertices = self._shape_vertices()

        v_size = np.amax(vertices, (0, 1)) - np.amin(vertices, (0, 1))
        vertices /= v_size
        vertices *= np.array((width, height))

        centroid = np.zeros(2)
        area = .0
        for vs in vertices:
            # compute centroid of polygon
            a = 0.5 * np.abs(
                np.dot(vs[:, 0], np.roll(vs[:, 1], 1)) -
                np.dot(vs[:, 1], np.roll(vs[:, 0], 1)))
            area += a
            centroid += vs.mean(axis=0) * a
        centroid /= area

        self.__local_vertices = vertices - centroid
        self.__local_vertices.setflags(write=False)

        for v in self.__local_vertices:
            self._body.CreatePolygonFixture(
                shape=Box2D.b2PolygonShape(vertices=(v *
                                                     _world_scale).tolist()),
                density=self._density,
                friction=self._friction,
                restitution=self._restitution,
                # radius=.00000001
            )

        self._fixture = self._body.fixtures
示例#53
0
文件: elements.py 项目: JuiP/Bridge
    def json_load(self, path, serialized=False):
        import json

        self.world.groundBody.userData = {"saveid": 0}

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

        # load bodies
        for body in worldmodel['bodylist']:
            bodyDef = box2d.b2BodyDef()
            if body['dynamic']:
                bodyDef.type = box2d.b2_dynamicBody
            bodyDef.position = body['position']
            bodyDef.userData = body['userData']
            bodyDef.angle = body['angle']
            newBody = self.world.CreateBody(bodyDef)
            # _logger.debug(newBody)
            newBody.angularVelocity = body['angularVelocity']
            newBody.linearVelocity = body['linearVelocity']
            if 'shapes' in body:
                for shape in body['shapes']:
                    if shape['type'] == 'polygon':
                        polyDef = box2d.b2FixtureDef()
                        polyShape = box2d.b2PolygonShape()
                        polyShape.vertices = shape['vertices']
                        polyDef.shape = polyShape
                        polyDef.density = shape['density']
                        polyDef.restitution = shape['restitution']
                        polyDef.friction = shape['friction']
                        newBody.CreateFixture(polyDef)
                    if shape['type'] == 'circle':
                        circleDef = box2d.b2FixtureDef()
                        circleShape = box2d.b2CircleShape()
                        circleShape.radius = shape['radius']
                        circleShape.pos = shape['localPosition']
                        circleDef.shape = circleShape
                        circleDef.density = shape['density']
                        circleDef.restitution = shape['restitution']
                        circleDef.friction = shape['friction']
                        newBody.CreateFixture(circleDef)

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

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

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

        self.additional_vars = addvars

        for body in self.world.bodies:
            del body.userData['saveid']  # remove temporary data
quakeFreq = 10
quakeVertical = False
quakeActive = False

###

pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32)
pygame.display.set_caption('GraviTask')
clock = pygame.time.Clock()

world = world(gravity=(0, -10), doSleep=True)

ground_shape = Box2D.b2PolygonShape(vertices = [(0 , 10),
                                                (2 , 1),
                                                (98 , 1),
                                                (100 , 10),
                                                (100 , 0),
                                                (0 , 0)])

ground_body = world.CreateStaticBody(
    position=(0, 0),
    shapes=(polygonShape(box=(100, 5))),
)

quakeFloor = world.CreateKinematicBody(position=(1 , 6))

quakeFloor.CreateFixture(shape=Box2D.b2PolygonShape(vertices=[(0 , 0),
                                                                      (0 , 1),
                                                                      (40 , 1),
                                                                      (40 , 0)])
                                 ,friction=4)
示例#55
0
import Box2D

# Part of this game
from dwarf import Dwarf
from block import Wood, Stone, Dirt
import ai

# Lets assume a conversion of 35 pixels/meter
# This means dwarves are about 2 meters tall
pxPerM = 35.0  # px/m
worldWidth = 640  # px
worldHeight = 480  # px
world = Box2D.b2World(gravity=(0, -10), doSleep=True)
groundBody = world.CreateStaticBody( \
        position=(worldWidth*pxPerM/2,worldHeight*pxPerM+5), \
        shapes=Box2D.b2PolygonShape(box=(worldWidth*pxPerM,10)))

screen = pygame.display.set_mode((worldWidth, worldHeight))
dwarfSkin = pygame.image.load('images/dwarf.png').convert()
dwarfSkin.set_colorkey((255, 0, 255))

background = 255, 255, 255

# Create the world
worldBlocks = pygame.sprite.Group()
for x in range(0, 640, 10):
    for y in range(50, 100, 10):
        newBlock = Dirt((x, y))
        worldBlocks.add(newBlock)
    for y in range(100, 400, 10):
        newBlock = Stone((x, y))
示例#56
0
###nose = [cV[15],cV[5],cV[6]]
#print nose
#for val1,val2 in tail:
#    print val1,val2
tailm = [(val1 / PPM, val2 / PPM) for val1, val2 in tail]
bottomm = [(val1 / PPM, val2 / PPM) for val1, val2 in bottom]
topm = [(val1 / PPM, val2 / PPM) for val1, val2 in top]
nosem = [(val1 / PPM, val2 / PPM) for val1, val2 in nose]
#print tailm
#print bottomm
body = world.CreateDynamicBody(
    position=(10, 10),
    angle=pi,
    angularDamping=5,
    linearDamping=0.1,
    shapes=[Box2D.b2PolygonShape(vertices=tailm)],
    #Box2D.b2PolygonShape(vertices=restm) ],
    shapeFixture=Box2D.b2FixtureDef(density=20.0),
)
#body=world.CreateDynamicBody(position=(13,10), angle=0)
#crusaderTail=body.CreatePolygonFixture(
#                                       Box2D.b2PolygonShape(vertices=[(-1,0), (1,0), (0,.5)])
#                                       , density=1, friction=0.3)

#body=world.CreateDynamicBody(position=(13,14), angle=0)
#crusaderTail=body.CreatePolygonFixture(rest, density=1, friction=0.3)

colors = {
    staticBody: (255, 255, 255, 255),
    dynamicBody: (127, 127, 127, 255),
}
示例#57
0
    def __init__(self, x0, target):
        super(Arm3World, self).__init__()

        self.world.gravity = (0.0, 0.0)

        fixture_length = 5.0
        self.x0 = x0

        rectangle_fixture = b2.b2FixtureDef(
            shape=b2.b2PolygonShape(box=(.5, fixture_length)),
            density=.5,
            friction=1,
        )
        square_fixture = b2.b2FixtureDef(
            shape=b2.b2PolygonShape(box=(1, 1)),
            density=100.0,
            friction=1,
        )
        self.base = self.world.CreateBody(
            position=(0, 15),
            fixtures=square_fixture,
        )

        self.body1 = self.world.CreateDynamicBody(
            position=(0, 2),
            fixtures=rectangle_fixture,
            angle=b2.b2_pi,
        )
        self.body2 = self.world.CreateDynamicBody(
            fixtures=rectangle_fixture,
            position=(0, 2),
            angle=b2.b2_pi,
        )
        self.body3 = self.world.CreateDynamicBody(
            fixtures=rectangle_fixture,
            position=(0, 2),
            angle=b2.b2_pi,
        )


        self.target1 = self.world.CreateDynamicBody(
            fixtures=rectangle_fixture,
            position=(0, 0),
            angle=b2.b2_pi,
        )
        self.target2 = self.world.CreateDynamicBody(
            fixtures=rectangle_fixture,
            position=(0, 0),
            angle=b2.b2_pi,
        )
        self.target3 = self.world.CreateDynamicBody(
            fixtures=rectangle_fixture,
            position=(0, 0),
            angle=b2.b2_pi,
        )

        self.joint1 = self.world.CreateRevoluteJoint(
            bodyA=self.base,
            bodyB=self.body1,
            localAnchorA=(0, 0),
            localAnchorB=(0, fixture_length),
            enableMotor=True,
            maxMotorTorque=400,
            enableLimit=False,
        )

        self.joint2 = self.world.CreateRevoluteJoint(
            bodyA=self.body1,
            bodyB=self.body2,
            localAnchorA=(0, -(fixture_length - 0.5)),
            localAnchorB=(0, fixture_length - 0.5),
            enableMotor=True,
            maxMotorTorque=400,
            enableLimit=False,
        )

        self.joint3 = self.world.CreateRevoluteJoint(
            bodyA=self.body2,
            bodyB=self.body3,
            localAnchorA=(0, -(fixture_length - 0.5)),
            localAnchorB=(0, fixture_length - 0.5),
            enableMotor=True,
            maxMotorTorque=400,
            enableLimit=False,
        )

        self.set_joint_angles(self.body1, self.body2, self.body3, x0[0], x0[1], x0[2] )
        self.set_joint_angles(self.target1, self.target2, self.target3, target[0], target[1], target[2] )
        self.target1.active = False
        self.target2.active = False

        self.joint1.motorSpeed = x0[3]
        self.joint2.motorSpeed = x0[4]
        self.joint3.motorSpeed = x0[5]