Ejemplo n.º 1
0
    def __init__(self):
        super(Raycast, self).__init__()

        self.world.gravity = (0, 0)
        # The ground
        ground = self.world.CreateBody(shapes=b2EdgeShape(vertices=[(-40, 0), (40, 0)]))

        # The various shapes
        w = 1.0
        b = w / (2.0 + sqrt(2.0))
        s = sqrt(2.0) * b

        self.shapes = [
            b2PolygonShape(vertices=[(-0.5, 0), (0.5, 0), (0, 1.5)]),
            b2PolygonShape(vertices=[(-0.1, 0), (0.1, 0), (0, 1.5)]),
            b2PolygonShape(
                vertices=[
                    (0.5 * s, 0),
                    (0.5 * w, b),
                    (0.5 * w, b + s),
                    (0.5 * s, w),
                    (-0.5 * s, w),
                    (-0.5 * w, b + s),
                    (-0.5 * w, b),
                    (-0.5 * s, 0.0),
                ]
            ),
            b2PolygonShape(box=(0.5, 0.5)),
            b2CircleShape(radius=0.5),
        ]
        self.angle = 0

        self.callbacks = [RayCastClosestCallback, RayCastAnyCallback, RayCastMultipleCallback]
        self.callback_class = self.callbacks[0]
Ejemplo n.º 2
0
def create_blob(world, center, radius, circle_radius=0.5, shape_num=24,
                angularDamping=0.5, linearDamping=0.5, friction=0.5,
                density=5.0, **kwargs):

    def get_pos(angle):
        return (cos(angle * pi / 180.0) * radius + center[0],
                sin(angle * pi / 180.0) * radius + center[1])

    circle = b2CircleShape(radius=circle_radius)
    fixture = b2FixtureDef(shape=circle, friction=friction, density=density,
                           restitution=0.0)

    bodies = [world.CreateDynamicBody(position=get_pos(
        i), fixtures=fixture) for i in range(0, 360, int(360 / shape_num))]
    joints = []

    prev_body = bodies[-1]
    for body in bodies:
        joint = world.CreateDistanceJoint(
            bodyA=prev_body,
            bodyB=body,
            anchorA=prev_body.position,
            anchorB=body.position,
            dampingRatio=10.0)

        joints.append(joint)
        prev_body = body

    return bodies, joints
Ejemplo n.º 3
0
    def __init__(self):
        super(OneSidedPlatform, self).__init__()

        # The ground
        ground = self.world.CreateBody(
            shapes=b2EdgeShape(vertices=[(-20, 0), (20, 0)])
        )

        # The platform
        half_height = 0.5
        ypos = 10
        body = self.world.CreateBody(
            position=(0, ypos),
            shapes=b2PolygonShape(box=(3, half_height))
        )
        self.platform = body.fixtures[0]

        # The circular character
        self.character_radius = 0.5
        body = self.world.CreateDynamicBody(
            position=(0, 12),
            fixtures=b2FixtureDef(shape=b2CircleShape(
                radius=self.character_radius), density=1.0),
        )

        self.character = body.fixtures[0]
        body.linearVelocity = (0, -50)

        self.bottom = ypos - half_height  # The bottom of the platform
        self.top = ypos + half_height    # The top of the platform
        self.state = 'unknown'
Ejemplo n.º 4
0
    def __init__(self):
        super(Liquid, self).__init__()

        self.per_particle_mass = self.total_mass / self.num_particles

        ground = self.world.CreateStaticBody(
            shapes=[
                b2PolygonShape(box=[5.0, 0.5]),
                b2PolygonShape(box=[1.0, 0.2, (0, 4), -0.2]),
                b2PolygonShape(box=[1.5, 0.2, (-1.2, 5.2), -1.5]),
                b2PolygonShape(box=[0.5, 50.0, (5, 0), 0.0]),
                b2PolygonShape(box=[0.5, 3.0, (-8, 0), 0.0]),
                b2PolygonShape(box=[2.0, 0.1, (-6, -2.8), 0.1]),
                b2CircleShape(radius=0.5, pos=(-.5, -4)),
            ]
        )

        cx = 0
        cy = 25
        box_width = 2.0
        box_height = 20.0
        self.liquid = []
        for i in range(self.num_particles):
            self.createDroplet((b2Random(cx - box_width * 0.5,
                                         cx + box_width * 0.5),
                                b2Random(cy - box_height * 0.5,
                                         cy + box_height * 0.5)))

        self.createBoxSurfer()

        if hasattr(self, 'settings'):
            self.settings.enableSubStepping = False
Ejemplo n.º 5
0
    def __init__(self):
        super(Bridge, self).__init__()

        # The ground
        ground = self.world.CreateBody(
            shapes=b2EdgeShape(vertices=[(-40, 0), (40, 0)])
        )

        create_bridge(self.world, ground, (1.0, 0.25),
                      (-14.5, 5), self.numPlanks, 0.2, 20)

        fixture = b2FixtureDef(
            shape=b2PolygonShape(vertices=[(-0.5, 0.0),
                                           (0.5, 0.0),
                                           (0.0, 1.5),
                                           ]),
            density=1.0
        )
        for i in range(2):
            self.world.CreateDynamicBody(
                position=(-8 + 8 * i, 12),
                fixtures=fixture,
            )

        fixture = b2FixtureDef(shape=b2CircleShape(radius=0.5), density=1)
        for i in range(3):
            self.world.CreateDynamicBody(
                position=(-6 + 6 * i, 10),
                fixtures=fixture,
            )
Ejemplo n.º 6
0
def create_car(world, offset, wheel_radius, wheel_separation, density=1.0,
               wheel_friction=0.9, scale=(1.0, 1.0), chassis_vertices=None,
               wheel_axis=(0.0, 1.0), wheel_torques=[20.0, 10.0],
               wheel_drives=[True, False], hz=4.0, zeta=0.7, **kwargs):
    """
    """
    x_offset, y_offset = offset
    scale_x, scale_y = scale
    if chassis_vertices is None:
        chassis_vertices = [
            (-1.5, -0.5),
            (1.5, -0.5),
            (1.5, 0.0),
            (0.0, 0.9),
            (-1.15, 0.9),
            (-1.5, 0.2),
        ]

    chassis_vertices = [(scale_x * x, scale_y * y)
                        for x, y in chassis_vertices]
    radius_scale = sqrt(scale_x ** 2 + scale_y ** 2)
    wheel_radius *= radius_scale

    chassis = world.CreateDynamicBody(
        position=(x_offset, y_offset),
        fixtures=b2FixtureDef(
            shape=b2PolygonShape(vertices=chassis_vertices),
            density=density,
        )
    )

    wheels, springs = [], []
    wheel_xs = [-wheel_separation * scale_x /
                2.0, wheel_separation * scale_x / 2.0]
    for x, torque, drive in zip(wheel_xs, wheel_torques, wheel_drives):
        wheel = world.CreateDynamicBody(
            position=(x_offset + x, y_offset - wheel_radius),
            fixtures=b2FixtureDef(
                shape=b2CircleShape(radius=wheel_radius),
                density=density,
            )
        )

        spring = world.CreateWheelJoint(
            bodyA=chassis,
            bodyB=wheel,
            anchor=wheel.position,
            axis=wheel_axis,
            motorSpeed=0.0,
            maxMotorTorque=torque,
            enableMotor=drive,
            frequencyHz=hz,
            dampingRatio=zeta
        )

        wheels.append(wheel)
        springs.append(spring)

    return chassis, wheels, springs
Ejemplo n.º 7
0
 def Keyboard(self, key):
     if key == Keys.K_b:
         if self.bullet:
             self.world.DestroyBody(self.bullet)
             self.bullet = None
         circle = b2FixtureDef(shape=b2CircleShape(radius=0.25), density=20, restitution=0.05)
         self.bullet = self.world.CreateDynamicBody(
             position=(-31, 5), bullet=True, fixtures=circle, linearVelocity=(400, 0)
         )
Ejemplo n.º 8
0
    def CreateCircle(self, pos):
        fixture = b2FixtureDef(shape=b2CircleShape(radius=self.radius,
                                                   pos=(0, 0)),
                               density=1, friction=0.1)

        self.world.CreateDynamicBody(
            position=pos,
            fixtures=fixture
        )
Ejemplo n.º 9
0
def create_cloth(world, segment_count, body_size, position=(0, 30),
                 group_index=-1, bar_height=0.5, base_hz=15,
                 base_damping=0.11, density=0.2):
    segment_w, segment_h = segment_count
    body_spacing_w = body_size * 2
    total_w = body_spacing_w * segment_w
    position = b2Vec2(*position)

    # The static bar at the top which holds the cloth
    bar = world.CreateStaticBody(position=position)
    bar.CreatePolygonFixture(box=(total_w / 2.0 + body_spacing_w,
                                  bar_height / 2.0),
                             groupIndex=group_index)

    box_fixture = b2FixtureDef(shape=b2CircleShape(radius=body_size),
                               groupIndex=group_index, density=density)

    weld_joints = []
    distance_joints = []
    cloth = [[None] * segment_h for x in range(segment_w)]
    for y in range(segment_h):
        pos = position - (total_w / 2.0, y * body_spacing_w)
        for x in range(segment_w):
            pos += (body_spacing_w, 0.0)
            body = world.CreateDynamicBody(position=pos, fixtures=box_fixture)
            cloth[x][y] = body

            if y == 0:
                joint = world.CreateWeldJoint(bodyA=body, bodyB=bar,
                                              anchor=body.position)
                weld_joints.append(joint)

    connect_bodies = []
    for y in range(segment_h):
        for x in range(segment_w):
            if x <= segment_w - 2:
                left_body = cloth[x][y]
                right_body = cloth[x + 1][y]
                connect_bodies.append((left_body, right_body))
            if y > 0:
                left_body = cloth[x][y]
                right_body = cloth[x][y - 1]
                connect_bodies.append((left_body, right_body))

    for bodyA, bodyB in connect_bodies:
        joint = world.CreateDistanceJoint(
            bodyA=bodyA,
            bodyB=bodyB,
            anchorA=bodyA.position,
            anchorB=bodyB.position,
            frequencyHz=base_hz + b2Random(0, base_hz / 2.0),
            dampingRatio=base_damping + b2Random(0.01, base_damping),
        )
        distance_joints.append(joint)

    return cloth, weld_joints, distance_joints
Ejemplo n.º 10
0
    def __init__(self):
        super(Pinball, self).__init__()

        # The ground
        ground = self.world.CreateBody(
            shapes=b2LoopShape(vertices=[(0, -2), (8, 6),
                                         (8, 20), (-8, 20),
                                         (-8, 6)]),
        )

        # Flippers
        p1, p2 = (-2, 0), (2, 0)

        fixture = b2FixtureDef(shape=b2PolygonShape(box=(1.75, 0.1)), density=1)
        flipper = {'fixtures': fixture}

        self.leftFlipper = self.world.CreateDynamicBody(
            position=p1,
            **flipper
        )
        self.rightFlipper = self.world.CreateDynamicBody(
            position=p2,
            **flipper
        )

        rjd = b2RevoluteJointDef(
            bodyA=ground,
            bodyB=self.leftFlipper,
            localAnchorA=p1,
            localAnchorB=(0, 0),
            enableMotor=True,
            enableLimit=True,
            maxMotorTorque=1000,
            motorSpeed=0,
            lowerAngle=-30.0 * b2_pi / 180.0,
            upperAngle=5.0 * b2_pi / 180.0,
        )

        self.leftJoint = self.world.CreateJoint(rjd)

        rjd.motorSpeed = 0
        rjd.localAnchorA = p2
        rjd.bodyB = self.rightFlipper
        rjd.lowerAngle = -5.0 * b2_pi / 180.0
        rjd.upperAngle = 30.0 * b2_pi / 180.0
        self.rightJoint = self.world.CreateJoint(rjd)

        # Ball
        self.ball = self.world.CreateDynamicBody(
            fixtures=b2FixtureDef(
                shape=b2CircleShape(radius=0.2),
                density=1.0),
            bullet=True,
            position=(1, 15))

        self.pressed = False
Ejemplo n.º 11
0
    def __init__(self, radius, centerpos, colour=None,
                 dens=1, frict=0.5, rest=0.25):

        b2_centerpos = get_b2pos(centerpos)
        r = radius / PPM
        self.body = world.CreateDynamicBody(position=b2_centerpos)
        
        circle = b2CircleShape(pos=(0, 0), radius=r)
        ball = self.body.CreateFixture(shape=circle, density=dens, friction=frict, restitution=rest)
        if not colour:
            self.colour = colour_x(gamma_min=150)
        else:
            self.colour = colour
Ejemplo n.º 12
0
    def __init__(self):
        super(EdgeShapes, self).__init__()
        self.ground = self.world.CreateStaticBody(
            shapes=[b2EdgeShape(vertices=v) for v in get_sinusoid_vertices(-20.0, VERTEX_COUNT)]
        )

        self.shapes = [
            b2PolygonShape(vertices=[(-0.5, 0), (0.5, 0), (0, 1.5)]),
            b2PolygonShape(vertices=[(-0.1, 0), (0.1, 0), (0, 1.5)]),
            b2PolygonShape(vertices=get_octagon_vertices(1.0)),
            b2PolygonShape(box=(0.5, 0.5)),
            b2CircleShape(radius=0.5),
        ]

        self.angle = 0
        self.callback = RayCastCallback()
Ejemplo n.º 13
0
    def LaunchBomb(self, position, velocity):
        """
        A bomb is a simple circle which has the specified position and velocity.
        position and velocity must be b2Vec2's.
        """
        if self.bomb:
            self.world.DestroyBody(self.bomb)
            self.bomb = None

        self.bomb = self.world.CreateDynamicBody(
            allowSleep=True,
            position=position,
            linearVelocity=velocity,
            fixtures=b2FixtureDef(shape=b2CircleShape(radius=0.3),
                                  density=20,
                                  restitution=0.1))
Ejemplo n.º 14
0
    def __init__(self):
        super(Pinball, self).__init__()

        # The ground
        ground = self.world.CreateBody(shapes=b2LoopShape(
            vertices=[(0, -2), (8, 6), (8, 20), (-8, 20), (-8, 6)]), )

        # Flippers
        p1, p2 = (-2, 0), (2, 0)

        fixture = b2FixtureDef(shape=b2PolygonShape(box=(1.75, 0.1)),
                               density=1)
        flipper = {'fixtures': fixture}

        self.leftFlipper = self.world.CreateDynamicBody(position=p1, **flipper)
        self.rightFlipper = self.world.CreateDynamicBody(position=p2,
                                                         **flipper)

        rjd = b2RevoluteJointDef(
            bodyA=ground,
            bodyB=self.leftFlipper,
            localAnchorA=p1,
            localAnchorB=(0, 0),
            enableMotor=True,
            enableLimit=True,
            maxMotorTorque=1000,
            motorSpeed=0,
            lowerAngle=-30.0 * b2_pi / 180.0,
            upperAngle=5.0 * b2_pi / 180.0,
        )

        self.leftJoint = self.world.CreateJoint(rjd)

        rjd.motorSpeed = 0
        rjd.localAnchorA = p2
        rjd.bodyB = self.rightFlipper
        rjd.lowerAngle = -5.0 * b2_pi / 180.0
        rjd.upperAngle = 30.0 * b2_pi / 180.0
        self.rightJoint = self.world.CreateJoint(rjd)

        # Ball
        self.ball = self.world.CreateDynamicBody(fixtures=b2FixtureDef(
            shape=b2CircleShape(radius=0.2), density=1.0),
                                                 bullet=True,
                                                 position=(1, 15))

        self.pressed = False
Ejemplo n.º 15
0
    def setupWorld(self):
        # circle shape
        shape = b2CircleShape(radius=50 / settings.B2D_PPM)

        # fixture
        fixture = b2FixtureDef()
        fixture.density = 1
        fixture.friction = 0.3
        fixture.shape = shape
        #fixture.userData = new UserDataInfo(name, bRadius * 2, bRadius * 2)

        # body definition
        bodyDef = b2BodyDef()
        bodyDef.position.Set((300) / settings.B2D_PPM,
                             (300) / settings.B2D_PPM)
        bodyDef.type = b2_dynamicBody
        bodyDef.fixedRotation = False

        circle = self.addActor(ActorB2D((300, 300), (50, 50)),
                               bodyDef=bodyDef,
                               fixture=fixture)

        box = self.addActor(ActorB2D((100, 400), (40, 20)), False)

        #j = self.m_b2dWorld.CreateRevoluteJoint(bodyA=box.m_body,
        #                                        bodyB=circle.m_body,
        #                                        localAnchorA=(0, 5),
        #                                        localAnchorB=(0, 0),
        #                                        enableMotor=False,
        #                                        maxMotorTorque=1000,
        #                                        enableLimit=True,
        #                                        lowerAngle=0,
        #                                        upperAngle=1)

        j = self.m_b2dWorld.CreateRevoluteJoint(
            bodyA=box.m_body,
            bodyB=circle.m_body,
            localAnchorA=(0, 5),
            localAnchorB=(0, 0),
            enableMotor=True,
            maxMotorTorque=1000,
            motorSpeed=1,  #rad/s
            enableLimit=False,
            lowerAngle=0,
            upperAngle=1)

        self.m_joints.append(j)
Ejemplo n.º 16
0
    def __init__(self):
        super(EdgeShapes, self).__init__()
        self.ground = self.world.CreateStaticBody(shapes=[
            b2EdgeShape(vertices=v)
            for v in get_sinusoid_vertices(-20.0, VERTEX_COUNT)
        ])

        self.shapes = [
            b2PolygonShape(vertices=[(-0.5, 0), (0.5, 0), (0, 1.5)]),
            b2PolygonShape(vertices=[(-0.1, 0), (0.1, 0), (0, 1.5)]),
            b2PolygonShape(vertices=get_octagon_vertices(1.0)),
            b2PolygonShape(box=(0.5, 0.5)),
            b2CircleShape(radius=0.5),
        ]

        self.angle = 0
        self.callback = RayCastCallback()
Ejemplo n.º 17
0
def create_vehicle(world, chassis_vertices, wheels_data):
    chassis_vertices = sorted(chassis_vertices, key=lambda cord: cord[0])
    shapes = [
        b2PolygonShape(
            vertices=[
                chassis_vertices[i],
                chassis_vertices[i + 1],
                chassis_vertices[i + 2],
                chassis_vertices[i + 3],
            ]
        )
        for i in range(0, len(chassis_vertices) - 2, 2)
    ]

    chassis = world.CreateDynamicBody(
        position=(0, 10),
        shapes=shapes,
        shapeFixture=b2FixtureDef(density=1, filter=b2Filter(groupIndex=-1)),
    )
    wheels, springs = [], []
    for wheel_spec in wheels_data:
        wheel = world.CreateDynamicBody(
            position=(wheel_spec["position_x"], wheel_spec["position_y"]),
            fixtures=b2FixtureDef(
                shape=b2CircleShape(radius=wheel_spec["radius"]),
                density=wheel_spec["density"],
                filter=b2Filter(groupIndex=-1),
            ),
        )

        spring = world.CreateWheelJoint(
            bodyA=chassis,
            bodyB=wheel,
            anchor=wheel.position,
            axis=(wheel_spec["wheel_axis_x"], wheel_spec["wheel_axis_y"]),
            motorSpeed=wheel_spec["speed"],
            maxMotorTorque=wheel_spec["torque"],
            enableMotor=wheel_spec["enable_motor"],
            dampingRatio=wheel_spec["damping_ratio"],
            frequencyHz=4.0,
        )

        wheels.append(wheel)
        springs.append(spring)
    return chassis, wheels, springs
    def __init__(self):
        super(Restitution, self).__init__()

        # The ground
        ground = self.world.CreateStaticBody(
            shapes=b2EdgeShape(vertices=[(-20, 0), (20, 0)])
        )

        radius = 1.0
        density = 1.0
        # The bodies
        for i, restitution in enumerate([0.0, 0.1, 0.3, 0.5, 0.75, 0.9, 1.0]):
            self.world.CreateDynamicBody(
                position=(-10 + 3.0 * i, 20),
                fixtures=b2FixtureDef(
                    shape=b2CircleShape(radius=radius),
                    density=density, restitution=restitution)
            )
Ejemplo n.º 19
0
    def __init__(self):
        super(Restitution, self).__init__()

        # The ground
        ground = self.world.CreateStaticBody(
            shapes=b2EdgeShape(vertices=[(-20, 0), (20, 0)])
        )

        radius = 1.0
        density = 1.0
        # The bodies
        for i, restitution in enumerate([0.0, 0.1, 0.3, 0.5, 0.75, 0.9, 1.0]):
            self.world.CreateDynamicBody(
                position=(-10 + 3.0 * i, 20),
                fixtures=b2FixtureDef(
                    shape=b2CircleShape(radius=radius),
                    density=density, restitution=restitution)
            )
Ejemplo n.º 20
0
    def LaunchBomb(self, position, velocity):
        """
        A bomb is a simple circle which has the specified position and velocity.
        position and velocity must be b2Vec2's.
        """
        if self.bomb:
            self.world.DestroyBody(self.bomb)
            self.bomb = None

        self.bomb = self.world.CreateDynamicBody(
            allowSleep=True,
            position=position,
            linearVelocity=velocity,
            fixtures=b2FixtureDef(
                shape=b2CircleShape(radius=0.3),
                density=20,
                restitution=0.1)

        )
Ejemplo n.º 21
0
    def __init__(self):
        super(TwoBallExample, self).__init__()
        self.world.gravity = (0.0, -10.0)

        # The boundaries
        ground = self.world.CreateBody(position=(0, 25.6))
        ground.CreateEdgeChain(
            [(-25.6, -25.6),
             (-25.6, 25.6),
             (25.6, 25.6),
             (25.6, -25.6),
             (-25.6, -25.6)]
        )

        fixtures = b2FixtureDef(shape=b2CircleShape(radius=1.0),
                                density=1, friction=0.3, restitution=0.5)

        body = self.world.CreateDynamicBody(
            position=(0, 10), fixtures=fixtures)
Ejemplo n.º 22
0
def new_physic_object(shape='box',
                      scale=1,
                      is_a_bullet=False,
                      pos=(0, 0),
                      angular_dampning=0,
                      linear_dampning=0,
                      category_bits=0x0001,
                      mask_bits=(0x0001 | 0x0002 | 0x0003),
                      den=2.0):

    debug_graphic = loader.loadModel("models/physic_square")
    debug_graphic.reparentTo(camera)
    if shape == 'circle':
        tex = loader.loadTexture("textures/round.png")
    else:
        tex = loader.loadTexture("textures/physic_texture.png")
    debug_graphic.setTexture(tex, 1)
    debug_graphic.setBin("unsorted", 0)
    debug_graphic.setDepthTest(False)
    if shape == 'box':
        new_shape = b2PolygonShape(
            box=(scale * defines.GRAPHIC_TO_PHYSIC_SCALE_RATIO,
                 scale * defines.GRAPHIC_TO_PHYSIC_SCALE_RATIO))
    elif shape == 'circle':
        new_shape = b2CircleShape(
            radius=(scale * defines.GRAPHIC_TO_PHYSIC_SCALE_RATIO))
    else:
        new_shape = b2PolygonShape(
            box=(scale * defines.GRAPHIC_TO_PHYSIC_SCALE_RATIO,
                 scale * defines.GRAPHIC_TO_PHYSIC_SCALE_RATIO))

    body = defines.world.CreateDynamicBody(position=pos,
                                           angle=0,
                                           angularDamping=angular_dampning,
                                           linearDamping=linear_dampning,
                                           shapes=new_shape,
                                           bullet=is_a_bullet,
                                           shapeFixture=b2FixtureDef(
                                               density=den,
                                               categoryBits=category_bits,
                                               maskBits=mask_bits))

    return debug_graphic, body
Ejemplo n.º 23
0
 def create_new_body(self):
     self.body = self.game.world.CreateDynamicBody(
         position=(
             self.x * self.game.physics_scale,
             self.y * self.game.physics_scale,
         ),
         userData=self,
     )
     fixture_def = b2FixtureDef(
         shape=b2CircleShape(radius=self.radius * self.game.physics_scale),
         friction=0.2,
         density=1.0,
         categoryBits=Category.ENEMY,
         maskBits=(Category.ENEMY
                   | Category.CHARACTER
                   | Category.CHARACTER_BULLET
                   | Category.WALL
                   | Category.CORPSE),
     )
     # noinspection PyUnusedLocal
     fixture = self.body.CreateFixture(fixture_def)
Ejemplo n.º 24
0
def replace_body(old_body, new_position, scale, shape='box',
                  category_bits=0x0001, mask_bits=(0x0001 | 0x0002 | 0x0003)):
    if shape == 'box':
        new_shape = b2PolygonShape(box=(scale * defines.GRAPHIC_TO_PHYSIC_SCALE_RATIO, scale * defines.GRAPHIC_TO_PHYSIC_SCALE_RATIO))
    elif shape == 'circle':
        new_shape= b2CircleShape(radius=(scale * defines.GRAPHIC_TO_PHYSIC_SCALE_RATIO))
    else:
        new_shape= b2PolygonShape(box=(scale * defines.GRAPHIC_TO_PHYSIC_SCALE_RATIO, scale * defines.GRAPHIC_TO_PHYSIC_SCALE_RATIO))
    
    new_body = defines.world.CreateDynamicBody(
            position=new_position,
            angle=old_body.angle,
            angularDamping=old_body.angularDamping,
            linearDamping=old_body.linearDamping,  
            shapes=new_shape,
            bullet=old_body.bullet,
            shapeFixture=b2FixtureDef(density=2.0,
                            categoryBits=category_bits,
                            maskBits=mask_bits  )
        )

    return new_body
Ejemplo n.º 25
0
 def __createCollisionBody(self, pos, size, shape, ud = None):
     #collisionbody       
     body = self.mWorld.CreateDynamicBody(position = pos)
     
     if shape == EnemyShape.CIRCLE:
         shape = b2CircleShape(radius=size.x/2)
     elif shape == EnemyShape.POLYGON:
         shape = b2PolygonShape()
         shape.SetAsBox(size.x/2, size.y/2)
     elif shape == EnemyShape.LINE:
         shape = b2EdgeShape()
         shape.vertices = b2Vec2(-size.x / 2.0, -size.y / 2.0), b2Vec2(size.x / 2.0, size.y / 2.0)        
     
     fd = b2FixtureDef()
     fd.shape = shape
     fd.isSensor = True
     body.CreateFixture(fd)
     body.isbullet = False
     body.fixedRotation = True
     body.userData = self if ud == None else ud
     
     return body
Ejemplo n.º 26
0
def create_blob(world,
                center,
                radius,
                circle_radius=0.5,
                shape_num=24,
                angularDamping=0.5,
                linearDamping=0.5,
                friction=0.5,
                density=5.0,
                **kwargs):
    def get_pos(angle):
        return (cos(angle * pi / 180.0) * radius + center[0],
                sin(angle * pi / 180.0) * radius + center[1])

    circle = b2CircleShape(radius=circle_radius)
    fixture = b2FixtureDef(shape=circle,
                           friction=friction,
                           density=density,
                           restitution=0.0)

    bodies = [
        world.CreateDynamicBody(position=get_pos(i), fixtures=fixture)
        for i in range(0, 360, int(360 / shape_num))
    ]
    joints = []

    prev_body = bodies[-1]
    for body in bodies:
        joint = world.CreateDistanceJoint(bodyA=prev_body,
                                          bodyB=body,
                                          anchorA=prev_body.position,
                                          anchorB=body.position,
                                          dampingRatio=10.0)

        joints.append(joint)
        prev_body = body

    return bodies, joints
Ejemplo n.º 27
0
    def __init__(self, position, physworld, gravity):
        self.mWorld = physworld
        self.mGravity = gravity
        self.mPlayerState = PlayerState.IDLE

        #create player physicsbody
        pos = b2Vec2(position[0] + self.PLAYER_WIDTH/5, position[1] + self.PLAYER_HEIGHT/2.5)
        body = self.mWorld.CreateDynamicBody(position = pos)
        shape = b2PolygonShape()
        fd = b2FixtureDef()
        fd.shape = shape
        fd.isSensor = True

        #footsensor
        shape.SetAsBox(self.PLAYER_WIDTH/5, 0.1, (0, 0.35), 0)
        fd.userData = Sensor.PLAYER_FOOTSENSOR
        body.CreateFixture(fd)

        #gravitysensor/deathsensor
        shape.SetAsBox(0.15,0.3)
        fd.userData = Sensor.PLAYER_DEATHSENSOR
        body.CreateFixture(fd)

        #footcollision
        shape = b2CircleShape(radius=0.2, pos=(0,0.15))
        fd.friction = 0
        fd.shape = shape
        fd.userData = self
        fd.isSensor = False
        body.CreateFixture(fd)

        #collisionbody
        body.CreatePolygonFixture(box=(self.PLAYER_WIDTH/5, self.PLAYER_HEIGHT/2.5), density=0, friction=0)
        body.bullet = True
        body.fixedRotation = True
        body.userData = self

        super(Player, self).__init__(pos, b2Vec2(self.PLAYER_WIDTH, self.PLAYER_HEIGHT), body, b2Vec2(0,0), 3.5, b2Vec2(0,0))
Ejemplo n.º 28
0
    def _reset(self):
        self._destroy()
        membrane_base.reset_helper(self)

        # Creating the object to manipulate
        object_fixture = b2FixtureDef(
            shape = b2CircleShape(radius=membrane_base.OBJ_SIZE/2),
            density = 0.3,
            friction = 0.6,
            restitution = 0.5
            )
        object_position = (self.np_random.uniform(membrane_base.OBJ_POS_OFFSET,membrane_base.BOX_WIDTH-membrane_base.OBJ_POS_OFFSET), membrane_base.BOX_HEIGHT/3)
        self.object = self.world.CreateDynamicBody(
            position = object_position,
            fixtures = object_fixture,
            linearDamping = 0.3 # Control this parameter for surface friction
            )
        self.object.color1 = (1,1,0)
        self.object.color2 = (0,0,0)

        self.drawlist = self.drawlist + [self.object]

        return self._step(np.array([0,0,0,0,0]))[0] # action: zero motor speed
Ejemplo n.º 29
0
    def __init__(self):
        super(VerticalStack, self).__init__()

        columns = 5
        rows = 16

        ground = self.world.CreateStaticBody(
            shapes=[b2EdgeShape(vertices=[(-40, 0), (40, 0)]), b2EdgeShape(vertices=[(20, 0), (20, 20)])]
        )

        box = b2FixtureDef(shape=b2PolygonShape(box=(0.5, 0.5)), density=1, friction=0.3)
        circle = b2FixtureDef(shape=b2CircleShape(radius=0.5), density=1, friction=0.3)

        box_start = -10
        box_space = 2.5
        circle_start = 8
        circle_space = 2.5
        for j in range(columns):
            for i in range(rows):
                self.world.CreateDynamicBody(fixtures=box, position=(box_start + box_space * j, 0.752 + 1.54 * i))
                self.world.CreateDynamicBody(
                    fixtures=circle, position=(circle_start + circle_space * j, 0.752 + 1.54 * i)
                )
Ejemplo n.º 30
0
    def __init__(self, **kwargs):
        super(flockSettings, self).__init__()

        # display
        self.render = False
        self.record = False
        self.record_dir = "../imgs/"
        self.verbose_display = True

        # environment
        self.start_spread = 20
        self.start_point = [0, 0]
        self.agent_rotation_speed = 0.8 * (2 * np.pi)
        self.agent_force = 20
        self.time_limit = 60

        circle = b2FixtureDef(shape=b2CircleShape(radius=0.5),
                              density=1,
                              friction=0.3)
        self.bodySettings = {
            "fixtures": circle,
            "linearDamping": 5,
            "fixedRotation": True
        }

        # task
        self.action_mode = "discrete"
        self.reward_mode = "binary"
        self._reward_radius = 7
        self.target_mindist = 25
        self.target_maxdist = 60
        self.coord = "polar"

        for kw in kwargs:
            setattr(self, kw, kwargs[kw])

        self.reward_radius = self._reward_radius if self.reward_mode == "binary" else 1
Ejemplo n.º 31
0
    def _reset(self):
        self._destroy()

        membrane_base.reset_helper(self)

        # Creating the object to manipulate
        object_fixture = b2FixtureDef(
            shape=b2CircleShape(radius=membrane_base.OBJ_SIZE / 2),
            density=0.3,
            friction=0.6,
            restitution=0.5)
        object_position = (membrane_base.BOX_WIDTH / 2,
                           membrane_base.OBJ_SIZE / 2 +
                           membrane_base.LINK_HEIGHT)
        self.object = self.world.CreateDynamicBody(
            position=object_position,
            fixtures=object_fixture,
            linearDamping=0.6  # Control this parameter for surface friction
        )
        self.object.color1 = (1, 1, 0)
        self.object.color2 = (0, 0, 0)

        self.drawlist = self.drawlist + [self.object]

        self.target_pos = [
            np.random.rand() *
            (membrane_base.BOX_WIDTH - membrane_base.OBJ_SIZE) +
            membrane_base.OBJ_SIZE / 2,
            np.random.rand() + 5
        ]

        for i in range(5):
            self.pd_control_list[i] = self.PDControl(PD_CONTROL_KP,
                                                     PD_CONTROL_KD)

        return self._step(np.array([0, 0, 0, 0,
                                    0]))[0]  # action: zero motor speed
Ejemplo n.º 32
0
    def __init__(self):
        super(VerticalStack, self).__init__()

        columns = 5
        rows = 16

        ground = self.world.CreateStaticBody(
            shapes=[
                b2EdgeShape(vertices=[(-40, 0), (40, 0)]),
                b2EdgeShape(vertices=[(20, 0), (20, 20)]),
            ]
        )

        box = b2FixtureDef(
            shape=b2PolygonShape(box=(0.5, 0.5)),
            density=1,
            friction=0.3)
        circle = b2FixtureDef(
            shape=b2CircleShape(radius=0.5),
            density=1,
            friction=0.3)

        box_start = -10
        box_space = 2.5
        circle_start = 8
        circle_space = 2.5
        for j in range(columns):
            for i in range(rows):
                self.world.CreateDynamicBody(
                    fixtures=box,
                    position=(box_start + box_space * j, 0.752 + 1.54 * i)
                )
                self.world.CreateDynamicBody(
                    fixtures=circle,
                    position=(circle_start + circle_space *
                              j, 0.752 + 1.54 * i)
                )
    def __init__(self):
        super(Raycast, self).__init__()

        self.world.gravity = (0, 0)
        # The ground
        ground = self.world.CreateBody(shapes=b2EdgeShape(vertices=[(-40,
                                                                     0), (40,
                                                                          0)]))

        # The various shapes
        w = 1.0
        b = w / (2.0 + sqrt(2.0))
        s = sqrt(2.0) * b

        self.shapes = [
            b2PolygonShape(vertices=[(-0.5, 0), (0.5, 0), (0, 1.5)]),
            b2PolygonShape(vertices=[(-0.1, 0), (0.1, 0), (0, 1.5)]),
            b2PolygonShape(
                vertices=[(0.5 * s,
                           0), (0.5 * w,
                                b), (0.5 * w,
                                     b + s), (0.5 * s,
                                              w), (-0.5 * s,
                                                   w), (-0.5 * w, b +
                                                        s), (-0.5 * w,
                                                             b), (-0.5 * s,
                                                                  0.0)]),
            b2PolygonShape(box=(0.5, 0.5)),
            b2CircleShape(radius=0.5),
        ]
        self.angle = 0

        self.callbacks = [
            RayCastClosestCallback, RayCastAnyCallback, RayCastMultipleCallback
        ]
        self.callback_class = self.callbacks[0]
Ejemplo n.º 34
0
def new_physic_object(shape='box', scale=1, 
                        is_a_bullet=False, pos=(0, 0), 
                        angular_dampning=0, linear_dampning=0,
                        category_bits=0x0001, mask_bits=(0x0001 | 0x0002 | 0x0003),
                        den=2.0):

    debug_graphic = loader.loadModel("models/physic_square")
    debug_graphic.reparentTo(camera)
    if shape == 'circle':
        tex = loader.loadTexture("textures/round.png")
    else:
        tex = loader.loadTexture("textures/physic_texture.png")
    debug_graphic.setTexture(tex, 1)
    debug_graphic.setBin("unsorted", 0)
    debug_graphic.setDepthTest(False)
    if shape == 'box':
        new_shape = b2PolygonShape(box=(scale * defines.GRAPHIC_TO_PHYSIC_SCALE_RATIO, scale * defines.GRAPHIC_TO_PHYSIC_SCALE_RATIO))
    elif shape == 'circle':
        new_shape= b2CircleShape(radius=(scale * defines.GRAPHIC_TO_PHYSIC_SCALE_RATIO))
    else:
        new_shape = b2PolygonShape(box=(scale * defines.GRAPHIC_TO_PHYSIC_SCALE_RATIO, scale * defines.GRAPHIC_TO_PHYSIC_SCALE_RATIO))
        
    
    body = defines.world.CreateDynamicBody(
            position=pos,
            angle=0,
            angularDamping=angular_dampning,
            linearDamping=linear_dampning,  
            shapes=new_shape,
            bullet=is_a_bullet,
            shapeFixture=b2FixtureDef(density=den,
                                    categoryBits=category_bits,
                                maskBits=mask_bits)
        )

    return debug_graphic, body
Ejemplo n.º 35
0
    def __init__(self):
        super(CollisionFiltering, self).__init__()
        # Ground body
        world = self.world
        ground = world.CreateBody(shapes=b2EdgeShape(vertices=[(-40, 0), (40,
                                                                          0)]))

        # Define the groups that fixtures can fall into
        # Note that negative groups never collide with other negative ones.
        smallGroup = 1
        largeGroup = -1

        # And the categories
        # Note that these are bit-locations, and as such are written in
        # hexadecimal.
        # defaultCategory = 0x0001
        triangleCategory = 0x0002
        boxCategory = 0x0004
        circleCategory = 0x0008

        # And the masks that define which can hit one another
        # A mask of 0xFFFF means that it will collide with everything else in
        # its group. The box mask below uses an exclusive OR (XOR) which in
        # effect toggles the triangleCategory bit, making boxMask = 0xFFFD.
        # Such a mask means that boxes never collide with triangles.  (if
        # you're still confused, see the implementation details below)

        triangleMask = 0xFFFF
        boxMask = 0xFFFF ^ triangleCategory
        circleMask = 0xFFFF

        # The actual implementation determining whether or not two objects
        # collide is defined in the C++ source code, but it can be overridden
        # in Python (with b2ContactFilter).
        # The default behavior goes like this:
        #   if (filterA.groupIndex == filterB.groupIndex and filterA.groupIndex != 0):
        #       collide if filterA.groupIndex is greater than zero (negative groups never collide)
        #   else:
        #       collide if (filterA.maskBits & filterB.categoryBits) != 0 and (filterA.categoryBits & filterB.maskBits) != 0
        #
        # So, if they have the same group index (and that index isn't the
        # default 0), then they collide if the group index is > 0 (since
        # negative groups never collide)
        # (Note that a body with the default filter settings will always
        # collide with everything else.)
        # If their group indices differ, then only if their bitwise-ANDed
        # category and mask bits match up do they collide.
        #
        # For more help, some basics of bit masks might help:
        # -> http://en.wikipedia.org/wiki/Mask_%28computing%29

        # Small triangle
        triangle = b2FixtureDef(
            shape=b2PolygonShape(vertices=[(-1, 0), (1, 0), (0, 2)]),
            density=1,
            filter=b2Filter(
                groupIndex=smallGroup,
                categoryBits=triangleCategory,
                maskBits=triangleMask,
            ))

        world.CreateDynamicBody(
            position=(-5, 2),
            fixtures=triangle,
        )

        # Large triangle (recycle definitions)
        triangle.shape.vertices = [
            2.0 * b2Vec2(v) for v in triangle.shape.vertices
        ]
        triangle.filter.groupIndex = largeGroup

        trianglebody = world.CreateDynamicBody(
            position=(-5, 6),
            fixtures=triangle,
            fixedRotation=True,  # <--
        )
        # note that the large triangle will not rotate

        # Small box
        box = b2FixtureDef(shape=b2PolygonShape(box=(1, 0.5)),
                           density=1,
                           restitution=0.1,
                           filter=b2Filter(
                               groupIndex=smallGroup,
                               categoryBits=boxCategory,
                               maskBits=boxMask,
                           ))

        world.CreateDynamicBody(
            position=(0, 2),
            fixtures=box,
        )

        # Large box
        box.shape.box = (2, 1)
        box.filter.groupIndex = largeGroup
        world.CreateDynamicBody(
            position=(0, 6),
            fixtures=box,
        )

        # Small circle
        circle = b2FixtureDef(shape=b2CircleShape(radius=1),
                              density=1,
                              filter=b2Filter(
                                  groupIndex=smallGroup,
                                  categoryBits=circleCategory,
                                  maskBits=circleMask,
                              ))

        world.CreateDynamicBody(
            position=(5, 2),
            fixtures=circle,
        )

        # Large circle
        circle.shape.radius *= 2
        circle.filter.groupIndex = largeGroup
        world.CreateDynamicBody(
            position=(5, 6),
            fixtures=circle,
        )

        # Create a joint for fun on the big triangle
        # Note that it does not inherit or have anything to do with the
        # filter settings of the attached triangle.
        box = b2FixtureDef(shape=b2PolygonShape(box=(0.5, 1)), density=1)

        testbody = world.CreateDynamicBody(
            position=(-5, 10),
            fixtures=box,
        )
        world.CreatePrismaticJoint(
            bodyA=trianglebody,
            bodyB=testbody,
            enableLimit=True,
            localAnchorA=(0, 4),
            localAnchorB=(0, 0),
            localAxisA=(0, 1),
            lowerTranslation=-1,
            upperTranslation=1,
        )
Ejemplo n.º 36
0
    def __init__(self):
        super(CollisionFiltering, self).__init__()
        # Ground body
        world = self.world
        ground = world.CreateBody(
            shapes=b2EdgeShape(vertices=[(-40, 0), (40, 0)])
        )

        # Define the groups that fixtures can fall into
        # Note that negative groups never collide with other negative ones.
        smallGroup = 1
        largeGroup = -1

        # And the categories
        # Note that these are bit-locations, and as such are written in
        # hexadecimal.
        # defaultCategory = 0x0001
        triangleCategory = 0x0002
        boxCategory = 0x0004
        circleCategory = 0x0008

        # And the masks that define which can hit one another
        # A mask of 0xFFFF means that it will collide with everything else in
        # its group. The box mask below uses an exclusive OR (XOR) which in
        # effect toggles the triangleCategory bit, making boxMask = 0xFFFD.
        # Such a mask means that boxes never collide with triangles.  (if
        # you're still confused, see the implementation details below)

        triangleMask = 0xFFFF
        boxMask = 0xFFFF ^ triangleCategory
        circleMask = 0xFFFF

        # The actual implementation determining whether or not two objects
        # collide is defined in the C++ source code, but it can be overridden
        # in Python (with b2ContactFilter).
        # The default behavior goes like this:
        #   if (filterA.groupIndex == filterB.groupIndex and filterA.groupIndex != 0):
        #       collide if filterA.groupIndex is greater than zero (negative groups never collide)
        #   else:
        #       collide if (filterA.maskBits & filterB.categoryBits) != 0 and (filterA.categoryBits & filterB.maskBits) != 0
        #
        # So, if they have the same group index (and that index isn't the
        # default 0), then they collide if the group index is > 0 (since
        # negative groups never collide)
        # (Note that a body with the default filter settings will always
        # collide with everything else.)
        # If their group indices differ, then only if their bitwise-ANDed
        # category and mask bits match up do they collide.
        #
        # For more help, some basics of bit masks might help:
        # -> http://en.wikipedia.org/wiki/Mask_%28computing%29

        # Small triangle
        triangle = b2FixtureDef(
            shape=b2PolygonShape(vertices=[(-1, 0), (1, 0), (0, 2)]),
            density=1,
            filter=b2Filter(
                groupIndex=smallGroup,
                categoryBits=triangleCategory,
                maskBits=triangleMask,
            )
        )

        world.CreateDynamicBody(
            position=(-5, 2),
            fixtures=triangle,
        )

        # Large triangle (recycle definitions)
        triangle.shape.vertices = [
            2.0 * b2Vec2(v) for v in triangle.shape.vertices]
        triangle.filter.groupIndex = largeGroup

        trianglebody = world.CreateDynamicBody(
            position=(-5, 6),
            fixtures=triangle,
            fixedRotation=True,  # <--
        )
        # note that the large triangle will not rotate

        # Small box
        box = b2FixtureDef(
            shape=b2PolygonShape(box=(1, 0.5)),
            density=1,
            restitution=0.1,
            filter = b2Filter(
                groupIndex=smallGroup,
                categoryBits=boxCategory,
                maskBits=boxMask,
            )
        )

        world.CreateDynamicBody(
            position=(0, 2),
            fixtures=box,
        )

        # Large box
        box.shape.box = (2, 1)
        box.filter.groupIndex = largeGroup
        world.CreateDynamicBody(
            position=(0, 6),
            fixtures=box,
        )

        # Small circle
        circle = b2FixtureDef(
            shape=b2CircleShape(radius=1),
            density=1,
            filter=b2Filter(
                groupIndex=smallGroup,
                categoryBits=circleCategory,
                maskBits=circleMask,
            )
        )

        world.CreateDynamicBody(
            position=(5, 2),
            fixtures=circle,
        )

        # Large circle
        circle.shape.radius *= 2
        circle.filter.groupIndex = largeGroup
        world.CreateDynamicBody(
            position=(5, 6),
            fixtures=circle,
        )

        # Create a joint for fun on the big triangle
        # Note that it does not inherit or have anything to do with the
        # filter settings of the attached triangle.
        box = b2FixtureDef(shape=b2PolygonShape(box=(0.5, 1)), density=1)

        testbody = world.CreateDynamicBody(
            position=(-5, 10),
            fixtures=box,
        )
        world.CreatePrismaticJoint(
            bodyA=trianglebody,
            bodyB=testbody,
            enableLimit=True,
            localAnchorA=(0, 4),
            localAnchorB=(0, 0),
            localAxisA=(0, 1),
            lowerTranslation=-1,
            upperTranslation=1,
        )
Ejemplo n.º 37
0
 def __init__(self, world, position, orientation, robot_color=(1.0, 0.0, 0.0), radius=3, type='kinematic'):
     # self.direction_vec = world.CreateKinematicBody(position=position, shape=[b2EdgeShape(vertices=[position, (radius*math.cos(orientation), radius*math.sin(orientation))])])
     self.robot = world.CreateKinematicBody(position=position, angle=orientation, shapes=[b2CircleShape(pos=position, radius=radius)])
     self.robot_color = robot_color
     self.radius = radius
Ejemplo n.º 38
0
    def __init__(self, args=None):
        """
        Initialize all of your objects here.
        Be sure to call the Framework's initializer first.
        """
        if args == None:
            args = {
                "start_y": 10,
                "len_torso": 6,
                "len_crank_arm": 2,
                "len_leg": 14,
                "motor_torque": 400,
                "motor_speed": 5
            }
        super(Robot, self).__init__()
        self.count = 0
        self.points = []
        self.group = -1
        self.start_y = args["start_y"]
        self.len_torso = args["len_torso"]
        self.len_crank_arm = args["len_crank_arm"]
        self.len_leg = args["len_leg"]
        self.motor_torque = args["motor_torque"]
        self.motor_speed = args["motor_speed"]
        #Non controlled constants
        torso_width = .001
        other_width = .001
        leg_angle = numpy.arctan(self.len_torso / self.len_crank_arm)
        ground = self.world.CreateStaticBody(
            position=(0, 0),
            shapes=[b2EdgeShape(vertices=[(-1000, 0), (1000, 0)])])

        self.torso = self.world.CreateDynamicBody(
            position=(0, self.start_y),
            fixedRotation=False,
            fixtures=b2FixtureDef(
                shape=b2PolygonShape(box=(torso_width, self.len_torso / 2)),
                density=1.3,
                filter=b2Filter(groupIndex=self.group, )),
        )
        tail_angle = -numpy.pi / 3
        len_tail = .035
        self.tail = self.world.CreateDynamicBody(
            position=(len_tail * numpy.sin(tail_angle),
                      self.start_y - len_tail * numpy.cos(tail_angle)),
            fixtures=b2FixtureDef(shape=b2PolygonShape(box=(torso_width,
                                                            len_tail)),
                                  density=1,
                                  filter=b2Filter(groupIndex=self.group, )),
            angle=tail_angle,
        )

        self.crank_arm = self.world.CreateDynamicBody(
            position=(0, self.start_y + self.len_torso / 2),
            fixtures=b2FixtureDef(shape=b2PolygonShape(box=(self.len_crank_arm,
                                                            other_width)),
                                  density=.1,
                                  filter=b2Filter(groupIndex=self.group, )),
        )
        #Creating the legs
        l = numpy.sqrt(self.len_torso**2 + self.len_crank_arm**2)
        x = (self.len_leg - 2 * l) * numpy.cos(leg_angle) / 2
        y = (self.len_leg - 2 * l) * numpy.sin(leg_angle) / 2
        self.right_leg = self.world.CreateDynamicBody(
            position=(x, self.start_y - y - self.len_torso / 2),
            angle=(-1 * leg_angle + numpy.pi / 2),
            fixtures=b2FixtureDef(shape=b2PolygonShape(box=(other_width,
                                                            self.len_leg / 2)),
                                  density=.50,
                                  filter=b2Filter(groupIndex=self.group),
                                  friction=1,
                                  restitution=0),
        )
        self.left_leg = self.world.CreateDynamicBody(
            position=(-x, self.start_y - y - self.len_torso / 2),
            angle=(leg_angle + numpy.pi / 2),
            fixtures=b2FixtureDef(shape=b2PolygonShape(box=(other_width,
                                                            self.len_leg / 2)),
                                  density=1.0,
                                  filter=b2Filter(groupIndex=self.group),
                                  friction=1,
                                  restitution=0),
        )
        self.right_foot = self.world.CreateDynamicBody(
            position=(self.len_leg / 2 * numpy.cos(leg_angle),
                      self.len_leg * numpy.sin(leg_angle)),
            fixtures=b2FixtureDef(shape=b2CircleShape(radius=.003),
                                  density=0.1,
                                  filter=b2Filter(groupIndex=self.group, )),
        )
        self.left_foot = self.world.CreateDynamicBody(
            position=(-1 * self.len_leg / 2 * numpy.cos(leg_angle),
                      self.len_leg * numpy.sin(leg_angle)),
            fixtures=b2FixtureDef(shape=b2CircleShape(radius=.003),
                                  density=0.1,
                                  filter=b2Filter(groupIndex=self.group, )),
        )
        slot_joint_right = self.world.CreateDynamicBody(
            position=(0, self.torso.worldCenter[1] - self.len_torso / 2),
            angle=(-1 * leg_angle + numpy.pi / 2),
            fixtures=b2FixtureDef(shape=b2CircleShape(radius=.0005),
                                  density=1.0,
                                  filter=b2Filter(groupIndex=self.group, )),
        )
        slot_joint_left = self.world.CreateDynamicBody(
            position=(0, self.torso.worldCenter[1] - self.len_torso / 2),
            angle=(leg_angle + numpy.pi / 2),
            fixtures=b2FixtureDef(shape=b2CircleShape(radius=.0005),
                                  density=1.0,
                                  filter=b2Filter(groupIndex=self.group, )),
        )
        #Attach Feat to legs
        self.right_foot_weld = self.world.CreateWeldJoint(
            bodyA=self.right_foot,
            bodyB=self.right_leg,
            anchor=(self.torso.worldCenter[0] +
                    self.len_leg / 2 * numpy.cos(leg_angle),
                    self.torso.worldCenter[1] +
                    self.len_leg * numpy.sin(leg_angle)),
        )
        self.left_foot_weld = self.world.CreateWeldJoint(
            bodyA=self.left_foot,
            bodyB=self.left_leg,
            anchor=(self.torso.worldCenter[0] -
                    self.len_leg / 2 * numpy.cos(leg_angle),
                    self.torso.worldCenter[1] +
                    self.len_leg * numpy.sin(leg_angle)),
        )
        #Motor Joint
        self.motor = self.world.CreateRevoluteJoint(
            bodyA=self.torso,
            bodyB=self.crank_arm,
            anchor=(self.torso.worldCenter[0],
                    self.torso.worldCenter[1] + self.len_torso / 2),
            motorSpeed=self.motor_speed,
            maxMotorTorque=self.motor_torque,
            enableMotor=True,
        )
        #Joints at end of pivot
        self.right_joint = self.world.CreateRevoluteJoint(
            bodyA=self.crank_arm,
            bodyB=self.right_leg,
            anchor=(self.crank_arm.worldCenter[0] - self.len_crank_arm,
                    self.crank_arm.worldCenter[1]),
        )
        self.left_joint = self.world.CreateRevoluteJoint(
            bodyA=self.crank_arm,
            bodyB=self.left_leg,
            anchor=(self.crank_arm.worldCenter[0] + self.len_crank_arm,
                    self.crank_arm.worldCenter[1]),
        )
        #Making the slot joint composed of rev joint and prismatic joints
        self.left_joint_rev = self.world.CreateRevoluteJoint(
            bodyA=slot_joint_right,
            bodyB=self.torso,
            anchor=(0, self.start_y - self.len_torso / 2),
        )
        self.right_joint_rev = self.world.CreateRevoluteJoint(
            bodyA=slot_joint_left,
            bodyB=self.torso,
            anchor=(0, self.start_y - self.len_torso / 2),
        )
        self.right_slide_pris = self.world.CreatePrismaticJoint(
            bodyA=slot_joint_right,
            bodyB=self.right_leg,
            anchor=(self.torso.worldCenter[0],
                    self.torso.worldCenter[0] - self.len_torso / 2),
            localAxisA=(0, 1),
        )
        self.left_slide_pris = self.world.CreatePrismaticJoint(
            bodyA=slot_joint_left,
            bodyB=self.left_leg,
            anchor=(self.torso.worldCenter[0],
                    self.torso.worldCenter[0] - self.len_torso / 2),
            localAxisA=(0, 1),
        )
        self.tail_joint = self.world.CreateWeldJoint(
            bodyA=self.tail,
            bodyB=self.torso,
            anchor=(0, self.start_y - self.len_torso / 2),
        )
Ejemplo n.º 39
0
    def __init__(self):
        super(CollisionProcessing, self).__init__()

        # Tell the framework we're going to use contacts, so keep track of them
        # every Step.
        self.using_contacts = True

        # Ground body
        world = self.world
        ground = world.CreateBody(shapes=b2EdgeShape(vertices=[(-50,
                                                                0), (50,
                                                                     0)], ))

        xlow, xhi = -5, 5
        ylow, yhi = 2, 35
        random_vector = lambda: b2Vec2(b2Random(xlow, xhi), b2Random(
            ylow, yhi))

        # Small triangle
        triangle = b2FixtureDef(
            shape=b2PolygonShape(vertices=[(-1, 0), (1, 0), (0, 2)]),
            density=1,
        )

        world.CreateBody(
            type=b2_dynamicBody,
            position=random_vector(),
            fixtures=triangle,
        )

        # Large triangle (recycle definitions)
        triangle.shape.vertices = [
            2.0 * b2Vec2(v) for v in triangle.shape.vertices
        ]

        tri_body = world.CreateBody(
            type=b2_dynamicBody,
            position=random_vector(),
            fixtures=triangle,
            fixedRotation=True,  # <--
        )
        # note that the large triangle will not rotate

        # Small box
        box = b2FixtureDef(
            shape=b2PolygonShape(box=(1, 0.5)),
            density=1,
            restitution=0.1,
        )

        world.CreateBody(
            type=b2_dynamicBody,
            position=random_vector(),
            fixtures=box,
        )

        # Large box
        box.shape.box = (2, 1)
        world.CreateBody(
            type=b2_dynamicBody,
            position=random_vector(),
            fixtures=box,
        )

        # Small circle
        circle = b2FixtureDef(
            shape=b2CircleShape(radius=1),
            density=1,
        )

        world.CreateBody(
            type=b2_dynamicBody,
            position=random_vector(),
            fixtures=circle,
        )

        # Large circle
        circle.shape.radius *= 2
        world.CreateBody(
            type=b2_dynamicBody,
            position=random_vector(),
            fixtures=circle,
        )
Ejemplo n.º 40
0
    def _reset(self):
        self._destroy()

        # Creating the Exterior Box that defines the 2D Plane
        self.exterior_box = self.world.CreateStaticBody(
            position=(0, 0), shapes=b2LoopShape(vertices=EXT_BOX_POLY))
        self.exterior_box.color1 = (0, 0, 0)
        self.exterior_box.color2 = (0, 0, 0)

        # Creating the object to manipulate
        object_fixture = b2FixtureDef(shape=b2CircleShape(radius=BOX_WIDTH *
                                                          OBJ_SIZE / 2),
                                      density=0.3,
                                      friction=0.6,
                                      restitution=0.5)
        # Randomizing object's initial position
        # object_position = (
        #     self.np_random.uniform(BOX_WIDTH*OBJ_POS_OFFSET,BOX_WIDTH-BOX_WIDTH*OBJ_POS_OFFSET),
        #     BOX_HEIGHT/5
        #     )
        # object_position = (
        #     self.np_random.uniform(BOX_WIDTH*OBJ_POS_OFFSET,BOX_WIDTH-BOX_WIDTH*OBJ_POS_OFFSET),
        #     self.np_random.uniform(BOX_WIDTH*OBJ_POS_OFFSET,BOX_HEIGHT-BOX_WIDTH*OBJ_POS_OFFSET)
        #     )
        object_position = (self.np_random.uniform(
            BOX_WIDTH * OBJ_POS_OFFSET,
            BOX_WIDTH - BOX_WIDTH * OBJ_POS_OFFSET), BOX_HEIGHT / 3)
        self.object = self.world.CreateDynamicBody(
            position=object_position,
            fixtures=object_fixture,
            linearDamping=0.3  # Control this parameter for surface friction
        )
        self.object.at_target = False
        self.object.at_target_count = 0
        self.object.color1 = (1, 1, 0)
        self.object.color2 = (0, 0, 0)

        # Creating 5 actuators
        actuator_fixture = b2FixtureDef(
            shape=b2CircleShape(radius=BOX_WIDTH * ACTUATOR_TIP_SIZE / 2),
            density=1,
            friction=0.6,
            restitution=0.0,
            groupIndex=-1)

        for i in range(5):
            actuator = self.world.CreateDynamicBody(
                position=((BOX_SIDE_OFFSET + GAP * i) * BOX_WIDTH, 0),
                fixtures=actuator_fixture)
            actuator.color1 = (0, 0, 0.5)
            actuator.color2 = (0, 0, 0)

            actuator.joint = self.world.CreatePrismaticJoint(
                bodyA=self.exterior_box,
                bodyB=actuator,
                anchor=actuator.position,
                axis=(0, 1),
                lowerTranslation=0,
                upperTranslation=ACTUATOR_TRANSLATION_MAX,
                enableLimit=True,
                maxMotorForce=1000.0,
                motorSpeed=0,
                enableMotor=True)

            self.actuator_list.append(actuator)

        self.drawlist = self.actuator_list + [self.object]

        if self.with_linkage:
            # Creating the linkages that will form the semi-flexible membrane
            link_fixture = b2FixtureDef(
                shape=b2PolygonShape(box=(LINK_WIDTH * BOX_WIDTH / 2,
                                          LINK_HEIGHT * BOX_WIDTH / 2)),
                density=1,
                friction=0.6,
                restitution=0.0,
                groupIndex=-1  # neg index to prevent collision
            )

            for i in range(4):
                link_left = self.world.CreateDynamicBody(
                    position=(BOX_WIDTH *
                              (BOX_SIDE_OFFSET + GAP * i + LINK_WIDTH / 2), 0),
                    fixtures=link_fixture)
                link_left.color1 = (0, 1, 1)
                link_left.color2 = (1, 0, 1)
                self.link_left_list.append(link_left)

                link_right = self.world.CreateDynamicBody(
                    position=(BOX_WIDTH * (BOX_SIDE_OFFSET + GAP *
                                           (i + 1) - LINK_WIDTH / 2), 0),
                    fixtures=link_fixture)
                link_right.color1 = (0, 1, 1)
                link_right.color2 = (1, 0, 1)
                self.link_right_list.append(link_right)

                joint_left = self.world.CreateRevoluteJoint(
                    bodyA=self.actuator_list[i],
                    bodyB=link_left,
                    anchor=self.actuator_list[i].worldCenter,
                    collideConnected=False)

                joint_right = self.world.CreateRevoluteJoint(
                    bodyA=self.actuator_list[i + 1],
                    bodyB=link_right,
                    anchor=self.actuator_list[i + 1].worldCenter,
                    collideConnected=False)

                joint_middle = self.world.CreatePrismaticJoint(
                    bodyA=link_left,
                    bodyB=link_right,
                    anchor=(link_right.position.x - BOX_WIDTH *
                            (LINK_WIDTH / 2 + LINK_HEIGHT / 2),
                            link_right.position.y),
                    axis=(1, 0),
                    lowerTranslation=0,
                    upperTranslation=BOX_WIDTH * LINK_WIDTH * 2 / 3,
                    enableLimit=True)
            # Adding linkages to the drawlist
            self.drawlist = self.link_left_list + self.link_right_list + self.drawlist

        return self._step(np.array([0, 0, 0, 0,
                                    0]))[0]  # action: zero motor speed
Ejemplo n.º 41
0
def create_car(world,
               offset,
               wheel_radius,
               wheel_separation,
               density=1.0,
               wheel_friction=0.9,
               scale=(1.0, 1.0),
               chassis_vertices=None,
               wheel_axis=(0.0, 1.0),
               wheel_torques=[20.0, 10.0],
               wheel_drives=[True, False],
               hz=4.0,
               zeta=0.7,
               **kwargs):
    """
    """
    x_offset, y_offset = offset
    scale_x, scale_y = scale
    if chassis_vertices is None:
        chassis_vertices = [
            (-1.5, -0.5),
            (1.5, -0.5),
            (1.5, 0.0),
            (0.0, 0.9),
            (-1.15, 0.9),
            (-1.5, 0.2),
        ]

    chassis_vertices = [(scale_x * x, scale_y * y)
                        for x, y in chassis_vertices]
    radius_scale = sqrt(scale_x**2 + scale_y**2)
    wheel_radius *= radius_scale

    chassis = world.CreateDynamicBody(
        position=(x_offset, y_offset),
        fixtures=b2FixtureDef(
            shape=b2PolygonShape(vertices=chassis_vertices),
            density=density,
        ))

    wheels, springs = [], []
    wheel_xs = [
        -wheel_separation * scale_x / 2.0, wheel_separation * scale_x / 2.0
    ]
    for x, torque, drive in zip(wheel_xs, wheel_torques, wheel_drives):
        wheel = world.CreateDynamicBody(
            position=(x_offset + x, y_offset - wheel_radius),
            fixtures=b2FixtureDef(
                shape=b2CircleShape(radius=wheel_radius),
                density=density,
            ))

        spring = world.CreateWheelJoint(bodyA=chassis,
                                        bodyB=wheel,
                                        anchor=wheel.position,
                                        axis=wheel_axis,
                                        motorSpeed=0.0,
                                        maxMotorTorque=torque,
                                        enableMotor=drive,
                                        frequencyHz=hz,
                                        dampingRatio=zeta)

        wheels.append(wheel)
        springs.append(spring)

    return chassis, wheels, springs
Ejemplo n.º 42
0
def nice_car(world,
             wheel_radius=1.2,
             density=1.0,
             offset=(0, 0),
             wheel_friction=0.9,
             wheel_axis=(0.0, 1.0),
             wheel_torques=[200.0, 10.0],
             wheel_drives=[True, False],
             hz=4.0,
             zeta=0.7,
             **kwargs):
    x_offset, y_offset = offset
    chassis = world.CreateDynamicBody(position=(x_offset, y_offset))
    chassis.CreatePolygonFixture(vertices=[(0, 0), (0, 2), (1, 3)],
                                 groupIndex=-1,
                                 density=1,
                                 friction=0.3,
                                 restitution=0.3)
    chassis.CreatePolygonFixture(vertices=[(0, 0), (1, 3), (3, 3)],
                                 groupIndex=-1,
                                 density=1,
                                 friction=0.3,
                                 restitution=0.3)
    chassis.CreatePolygonFixture(vertices=[(0, 0), (3, 3), (2, 1)],
                                 groupIndex=-1,
                                 density=1,
                                 friction=0.3,
                                 restitution=0.3)
    chassis.CreatePolygonFixture(vertices=[(0, 0), (2, 1), (4, 0)],
                                 groupIndex=-1,
                                 density=1,
                                 friction=0.3,
                                 restitution=0.3)
    chassis.CreatePolygonFixture(vertices=[(0, 0), (4, 0), (1, -1)],
                                 groupIndex=-1,
                                 density=1,
                                 friction=0.3,
                                 restitution=0.3)
    chassis.CreatePolygonFixture(vertices=[(0, 0), (1, -1), (1, -3)],
                                 groupIndex=-1,
                                 density=1,
                                 friction=0.3,
                                 restitution=0.3)
    chassis.CreatePolygonFixture(vertices=[(0, 0), (1, -3), (-1, -1)],
                                 groupIndex=-1,
                                 density=1,
                                 friction=0.3,
                                 restitution=0.3)
    chassis.CreatePolygonFixture(vertices=[(0, 0), (-1, -1), (-3, 0)],
                                 groupIndex=-1,
                                 density=1,
                                 friction=0.3,
                                 restitution=0.3)
    chassis.CreatePolygonFixture(vertices=[(0, 0), (-3, 0), (-2, 2)],
                                 groupIndex=-1,
                                 density=1,
                                 friction=0.3,
                                 restitution=0.3)
    chassis.CreatePolygonFixture(vertices=[(0, 0), (-2, 2), (0, 2)],
                                 groupIndex=-1,
                                 density=1,
                                 friction=0.3,
                                 restitution=0.3)
    wheels, springs = [], []
    wheel = world.CreateDynamicBody(
        position=(x_offset + 1, y_offset - wheel_radius - 3),
        fixtures=b2FixtureDef(
            shape=b2CircleShape(radius=wheel_radius),
            density=density,
            groupIndex=-1,
            friction=1000,
        ))
    spring = world.CreateWheelJoint(
        bodyA=chassis,
        bodyB=wheel,
        localAnchorA=(1, -3),
        localAnchorB=(0, 0),
        axis=(1, 0),
        motorSpeed=-10,
        maxMotorTorque=200,
        enableMotor=False,
        frequencyHz=60,
        dampingRatio=1.0,
    )
    wheels.append(wheel)
    springs.append(spring)
    wheel = world.CreateDynamicBody(
        position=(x_offset - 3, y_offset - wheel_radius - 0),
        fixtures=b2FixtureDef(shape=b2CircleShape(radius=wheel_radius),
                              density=density,
                              groupIndex=-1))
    spring = world.CreateWheelJoint(bodyA=chassis,
                                    bodyB=wheel,
                                    localAnchorA=(-3, 0),
                                    localAnchorB=(0, 0),
                                    motorSpeed=-10,
                                    axis=(1, 0),
                                    maxMotorTorque=200,
                                    enableMotor=False,
                                    frequencyHz=60,
                                    dampingRatio=1.0)
    wheels.append(wheel)
    springs.append(spring)
    return springs
Ejemplo n.º 43
0
    def __init__(self):
        super(CharacterCollision, self).__init__()

        ground = self.world.CreateStaticBody(
            position=(0, 0),
            shapes=b2EdgeShape(vertices=[(-20, 0), (20, 0)])
        )

        # Collinear edges
        self.world.CreateStaticBody(
            shapes=[b2EdgeShape(vertices=[(-8, 1), (-6, 1)]),
                    b2EdgeShape(vertices=[(-6, 1), (-4, 1)]),
                    b2EdgeShape(vertices=[(-4, 1), (-2, 1)]),
                    ]
        )

        # Square tiles
        self.world.CreateStaticBody(
            shapes=[b2PolygonShape(box=[1, 1, (4, 3), 0]),
                    b2PolygonShape(box=[1, 1, (6, 3), 0]),
                    b2PolygonShape(box=[1, 1, (8, 3), 0]),
                    ]
        )

        # Square made from an edge loop. Collision should be smooth.
        body = self.world.CreateStaticBody()
        body.CreateLoopFixture(vertices=[(-1, 3), (1, 3), (1, 5), (-1, 5)])

        # Edge loop.
        body = self.world.CreateStaticBody(position=(-10, 4))
        body.CreateLoopFixture(vertices=[
            (0.0, 0.0), (6.0, 0.0),
            (6.0, 2.0), (4.0, 1.0),
            (2.0, 2.0), (0.0, 2.0),
            (-2.0, 2.0), (-4.0, 3.0),
            (-6.0, 2.0), (-6.0, 0.0), ]
        )

        # Square character 1
        self.world.CreateDynamicBody(
            position=(-3, 8),
            fixedRotation=True,
            allowSleep=False,
            fixtures=b2FixtureDef(shape=b2PolygonShape(
                box=(0.5, 0.5)), density=20.0),
        )

        # Square character 2
        body = self.world.CreateDynamicBody(
            position=(-5, 5),
            fixedRotation=True,
            allowSleep=False,
        )

        body.CreatePolygonFixture(box=(0.25, 0.25), density=20.0)

        # Hexagon character
        a = b2_pi / 3.0
        self.world.CreateDynamicBody(
            position=(-5, 8),
            fixedRotation=True,
            allowSleep=False,
            fixtures=b2FixtureDef(
                shape=b2PolygonShape(
                    vertices=[(0.5 * cos(i * a), 0.5 * sin(i * a))
                              for i in range(6)]),
                density=20.0
            ),
        )

        # Circle character
        self.world.CreateDynamicBody(
            position=(3, 5),
            fixedRotation=True,
            allowSleep=False,
            fixtures=b2FixtureDef(
                shape=b2CircleShape(radius=0.5),
                density=20.0
            ),
        )
Ejemplo n.º 44
0
    def __init__(self):
        super(TheoJansen, self).__init__()

        #
        ball_count = 40
        pivot = b2Vec2(0, 0.8)

        # The ground
        ground = self.world.CreateStaticBody(
            shapes=[
                b2EdgeShape(vertices=[(-50, 0), (50, 0)]),
                b2EdgeShape(vertices=[(-50, 0), (-50, 10)]),
                b2EdgeShape(vertices=[(50, 0), (50, 10)]),
            ]
        )

        box = b2FixtureDef(
            shape=b2PolygonShape(box=(0.5, 0.5)),
            density=1,
            friction=0.3)
        circle = b2FixtureDef(
            shape=b2CircleShape(radius=0.25),
            density=1)

        # Create the balls on the ground
        for i in range(ball_count):
            self.world.CreateDynamicBody(
                fixtures=circle,
                position=(-40 + 2.0 * i, 0.5),
            )

        # The chassis
        chassis_fixture = b2FixtureDef(
            shape=b2PolygonShape(box=(2.5, 1)),
            density=1,
            friction=0.3,
            groupIndex=-1)

        self.chassis = self.world.CreateDynamicBody(
            fixtures=chassis_fixture,
            position=pivot + self.offset)

        # Chassis wheel
        wheel_fixture = b2FixtureDef(
            shape=b2CircleShape(radius=1.6),
            density=1,
            friction=0.3,
            groupIndex=-1)

        self.wheel = self.world.CreateDynamicBody(
            fixtures=wheel_fixture,
            position=pivot + self.offset)

        # Add a joint between the chassis wheel and the chassis itself
        self.motorJoint = self.world.CreateRevoluteJoint(
            bodyA=self.wheel,
            bodyB=self.chassis,
            anchor=pivot + self.offset,
            collideConnected=False,
            motorSpeed=self.motorSpeed,
            maxMotorTorque=400,
            enableMotor=self.motorOn)

        wheelAnchor = pivot + (0, -0.8)
        self.CreateLeg(-1, wheelAnchor)
        self.CreateLeg(1, wheelAnchor)

        self.wheel.transform = (self.wheel.position, 120.0 * b2_pi / 180)
        self.CreateLeg(-1, wheelAnchor)
        self.CreateLeg(1, wheelAnchor)

        self.wheel.transform = (self.wheel.position, -120.0 * b2_pi / 180)
        self.CreateLeg(-1, wheelAnchor)
        self.CreateLeg(1, wheelAnchor)
Ejemplo n.º 45
0
    def __init__(self):
        super(TheoJansen, self).__init__()

        #
        ball_count = 40
        pivot = b2Vec2(0, 0.8)

        # The ground
        ground = self.world.CreateStaticBody(
            shapes=[
                b2EdgeShape(vertices=[(-50, 0), (50, 0)]),
                b2EdgeShape(vertices=[(-50, 0), (-50, 10)]),
                b2EdgeShape(vertices=[(50, 0), (50, 10)]),
            ]
        )

        box = b2FixtureDef(
            shape=b2PolygonShape(box=(0.5, 0.5)),
            density=1,
            friction=0.3)
        circle = b2FixtureDef(
            shape=b2CircleShape(radius=0.25),
            density=1)

        # Create the balls on the ground
        for i in range(ball_count):
            self.world.CreateDynamicBody(
                fixtures=circle,
                position=(-40 + 2.0 * i, 0.5),
            )

        # The chassis
        chassis_fixture = b2FixtureDef(
            shape=b2PolygonShape(box=(2.5, 1)),
            density=1,
            friction=0.3,
            groupIndex=-1)

        self.chassis = self.world.CreateDynamicBody(
            fixtures=chassis_fixture,
            position=pivot + self.offset)

        # Chassis wheel
        wheel_fixture = b2FixtureDef(
            shape=b2CircleShape(radius=1.6),
            density=1,
            friction=0.3,
            groupIndex=-1)

        self.wheel = self.world.CreateDynamicBody(
            fixtures=wheel_fixture,
            position=pivot + self.offset)

        # Add a joint between the chassis wheel and the chassis itself
        self.motorJoint = self.world.CreateRevoluteJoint(
            bodyA=self.wheel,
            bodyB=self.chassis,
            anchor=pivot + self.offset,
            collideConnected=False,
            motorSpeed=self.motorSpeed,
            maxMotorTorque=400,
            enableMotor=self.motorOn)

        wheelAnchor = pivot + (0, -0.8)
        self.CreateLeg(-1, wheelAnchor)
        self.CreateLeg(1, wheelAnchor)

        self.wheel.transform = (self.wheel.position, 120.0 * b2_pi / 180)
        self.CreateLeg(-1, wheelAnchor)
        self.CreateLeg(1, wheelAnchor)

        self.wheel.transform = (self.wheel.position, -120.0 * b2_pi / 180)
        self.CreateLeg(-1, wheelAnchor)
        self.CreateLeg(1, wheelAnchor)
Ejemplo n.º 46
0
    def _reset(self):
        self._destroy()
        self.game_over = False  # To be used later

        # Creating the Exterior Box that defines the 2D Plane
        self.exterior_box = self.world.CreateStaticBody(
            position=(0, 0), shapes=b2LoopShape(vertices=EXT_BOX_POLY))
        self.exterior_box.color1 = (0, 0, 0)
        self.exterior_box.color2 = (0, 0, 0)

        # Creating the object to manipulate
        object_fixture = b2FixtureDef(shape=b2CircleShape(radius=BOX_WIDTH /
                                                          20),
                                      density=1,
                                      friction=0.6)

        self.object = self.world.CreateDynamicBody(position=(5,
                                                             BOX_HEIGHT / 2),
                                                   fixtures=object_fixture)
        self.object.at_target = False
        self.object.at_target_count = 0
        self.object.color1 = (1, 1, 0)
        self.object.color2 = (0, 0, 0)

        # Creating 5 actuators
        self.actuator_list = []
        self.actuator_joint_list = []

        actuator_fixture = b2FixtureDef(shape=b2CircleShape(radius=BOX_WIDTH /
                                                            50.0),
                                        density=1,
                                        friction=0.6,
                                        groupIndex=-1)

        for i in range(5):
            actuator = self.world.CreateDynamicBody(
                position=(BOX_WIDTH / 5 * i + BOX_WIDTH / 10, BOX_HEIGHT / 10),
                fixtures=actuator_fixture)
            actuator.color1 = (1, 0, 0)
            actuator.color2 = (1, 0, 0)

            #SHOULD STAY COMMENTED
            # actuator = self.world.CreateKinematicBody(
            #     position = (BOX_WIDTH/5*i+BOX_WIDTH/10, BOX_HEIGHT/10),
            #     shapes = b2CircleShape(radius=BOX_WIDTH/50.0), # diameter is 1/5th of the space allocated for each actuator
            #     )

            actuator_joint = self.world.CreatePrismaticJoint(
                bodyA=self.exterior_box,
                bodyB=actuator,
                anchor=actuator.position,
                axis=(0, 1),
                lowerTranslation=0,
                upperTranslation=ACTUATOR_TRANSLATION_MAX,
                enableLimit=True,
                maxMotorForce=1000.0,
                motorSpeed=0,
                enableMotor=True)

            self.actuator_list.append(actuator)
            self.actuator_joint_list.append(actuator_joint)

        # Creating the linkages that will form the semi-flexible membrane
        self.link_left_list = []  # four links
        self.link_right_list = []  # four links

        link_fixture = b2FixtureDef(
            shape=b2PolygonShape(box=(BOX_WIDTH / 12, BOX_WIDTH / 70.0)),
            density=1,
            friction=0.6,
            groupIndex=-1  # neg index to prevent collision
        )

        for i in range(1, 5):
            link_left = self.world.CreateDynamicBody(
                position=(BOX_WIDTH / 5 * i - BOX_WIDTH / 10 + BOX_WIDTH / 12,
                          BOX_HEIGHT / 10),
                fixtures=link_fixture)
            link_left.color1 = (0, 1, 1)
            link_left.color2 = (1, 0, 1)
            self.link_left_list.append(link_left)

            link_right = self.world.CreateDynamicBody(
                position=(BOX_WIDTH / 5 * i + BOX_WIDTH / 10 - BOX_WIDTH / 12,
                          BOX_HEIGHT / 10),
                fixtures=link_fixture)
            link_right.color1 = (0, 1, 1)
            link_right.color2 = (1, 0, 1)
            self.link_right_list.append(link_right)

            joint_left = self.world.CreateRevoluteJoint(
                bodyA=self.actuator_list[i - 1],
                bodyB=link_left,
                anchor=self.actuator_list[i - 1].worldCenter,
                collideConnected=False)

            joint_right = self.world.CreateRevoluteJoint(
                bodyA=self.actuator_list[i],
                bodyB=link_right,
                anchor=self.actuator_list[i].worldCenter,
                collideConnected=False)

            joint_middle = self.world.CreatePrismaticJoint(
                bodyA=link_left,
                bodyB=link_right,
                anchor=(link_right.position.x - BOX_WIDTH / 12 +
                        BOX_WIDTH / 70, link_right.position.y),
                axis=(1, 0),
                lowerTranslation=0,
                upperTranslation=BOX_WIDTH / 6 - BOX_WIDTH / 35,
                enableLimit=True)

        self.drawlist = self.link_right_list + self.link_left_list + [
            self.object
        ]
        self.drawlist = self.drawlist + self.actuator_list
        return self._step(np.array([0, 0, 0, 0,
                                    0]))[0]  # action: zero motor speed
Ejemplo n.º 47
0
    def __init__(self):
        super(Cantilever, self).__init__()

        # The ground
        ground = self.world.CreateBody(
            shapes=b2EdgeShape(vertices=[(-40, 0), (40, 0)]))

        plank = b2FixtureDef(
            shape=b2PolygonShape(box=(0.5, 0.125)),
            friction=0.2,
            density=20
        )

        # Create one cantilever (Only the left end is fixed)
        prevBody = ground
        for i in range(self.numPlanks):
            body = self.world.CreateDynamicBody(
                position=(-14.5 + i, 5),
                fixtures=plank,
            )

            self.world.CreateWeldJoint(
                bodyA=prevBody,
                bodyB=body,
                anchor=(-15 + i, 5),
            )

            prevBody = body

        # Create another higher up
        prevBody = ground
        for i in range(self.numPlanks):
            body = self.world.CreateDynamicBody(
                position=(-14.5 + i, 15),
                fixtures=plank,
            )

            self.world.CreateWeldJoint(
                bodyA=prevBody,
                bodyB=body,
                anchor=(-15 + i, 15),
            )

            prevBody = body

        # And the left-most unconnected one (technically not a cantilever)
        prevBody = ground
        for i in range(self.numPlanks):
            body = self.world.CreateDynamicBody(
                position=(-4.5 + i, 5),
                fixtures=plank,
            )

            if i > 0:  # skip the joint on the first one
                self.world.CreateWeldJoint(
                    bodyA=prevBody,
                    bodyB=body,
                    anchor=(-5 + i, 5),
                )

            prevBody = body

        # And the right-most unconnected one, using joint damping
        prevBody = ground
        for i in range(self.numPlanks):
            body = self.world.CreateDynamicBody(
                position=(5.5 + i, 10),
                fixtures=plank,
            )

            if i > 0:  # skip the joint on the first one
                self.world.CreateWeldJoint(
                    bodyA=prevBody,
                    bodyB=body,
                    anchor=(5 + i, 10),
                    frequencyHz=8.0,
                    dampingRatio=0.7,
                )

            prevBody = body

        # And a few random shapes to play with
        # First a set of triangles,
        fixture = b2FixtureDef(shape=b2PolygonShape(vertices=[(-0.5, 0.0),
                                                              (0.5, 0.0),
                                                              (0.0, 1.5),
                                                              ]),
                               density=1.0)
        for i in range(2):
            self.world.CreateDynamicBody(
                position=(-8 + 8 * i, 12),
                fixtures=fixture,
            )

        # And then a few circles
        fixture = b2FixtureDef(shape=b2CircleShape(radius=0.5), density=1)
        for i in range(3):
            self.world.CreateDynamicBody(
                position=(-6 + 6 * i, 10),
                fixtures=fixture,
            )
Ejemplo n.º 48
0
    def __init__(self):
        super(Cantilever, self).__init__()

        # The ground
        ground = self.world.CreateBody(shapes=b2EdgeShape(vertices=[(-40,
                                                                     0), (40,
                                                                          0)]))

        plank = b2FixtureDef(shape=b2PolygonShape(box=(0.5, 0.125)),
                             friction=0.2,
                             density=20)

        # Create one cantilever (Only the left end is fixed)
        prevBody = ground
        for i in range(self.numPlanks):
            body = self.world.CreateDynamicBody(
                position=(-14.5 + i, 5),
                fixtures=plank,
            )

            self.world.CreateWeldJoint(
                bodyA=prevBody,
                bodyB=body,
                anchor=(-15 + i, 5),
            )

            prevBody = body

        # Create another higher up
        prevBody = ground
        for i in range(self.numPlanks):
            body = self.world.CreateDynamicBody(
                position=(-14.5 + i, 15),
                fixtures=plank,
            )

            self.world.CreateWeldJoint(
                bodyA=prevBody,
                bodyB=body,
                anchor=(-15 + i, 15),
            )

            prevBody = body

        # And the left-most unconnected one (technically not a cantilever)
        prevBody = ground
        for i in range(self.numPlanks):
            body = self.world.CreateDynamicBody(
                position=(-4.5 + i, 5),
                fixtures=plank,
            )

            if i > 0:  # skip the joint on the first one
                self.world.CreateWeldJoint(
                    bodyA=prevBody,
                    bodyB=body,
                    anchor=(-5 + i, 5),
                )

            prevBody = body

        # And the right-most unconnected one, using joint damping
        prevBody = ground
        for i in range(self.numPlanks):
            body = self.world.CreateDynamicBody(
                position=(5.5 + i, 10),
                fixtures=plank,
            )

            if i > 0:  # skip the joint on the first one
                self.world.CreateWeldJoint(
                    bodyA=prevBody,
                    bodyB=body,
                    anchor=(5 + i, 10),
                    frequencyHz=8.0,
                    dampingRatio=0.7,
                )

            prevBody = body

        # And a few random shapes to play with
        # First a set of triangles,
        fixture = b2FixtureDef(shape=b2PolygonShape(vertices=[
            (-0.5, 0.0),
            (0.5, 0.0),
            (0.0, 1.5),
        ]),
                               density=1.0)
        for i in range(2):
            self.world.CreateDynamicBody(
                position=(-8 + 8 * i, 12),
                fixtures=fixture,
            )

        # And then a few circles
        fixture = b2FixtureDef(shape=b2CircleShape(radius=0.5), density=1)
        for i in range(3):
            self.world.CreateDynamicBody(
                position=(-6 + 6 * i, 10),
                fixtures=fixture,
            )
Ejemplo n.º 49
0
def reset_helper(env_obj):

    # Creating the Exterior Box that defines the 2D Plane
    env_obj.exterior_box = env_obj.world.CreateStaticBody(
        position=(0, 0), shapes=b2LoopShape(vertices=EXT_BOX_POLY))
    env_obj.exterior_box.color1 = (0, 0, 0)
    env_obj.exterior_box.color2 = (0, 0, 0)

    # Creating 5 actuators
    actuator_fixture = b2FixtureDef(
        shape=b2CircleShape(radius=ACTUATOR_TIP_SIZE / 2),
        density=1,
        friction=0.6,
        restitution=0.0,
        groupIndex=-1)

    for i in range(5):
        actuator = env_obj.world.CreateDynamicBody(position=(BOX_SIDE_OFFSET +
                                                             GAP * i, 0),
                                                   fixtures=actuator_fixture)
        actuator.color1 = (0, 0, 0.5)
        actuator.color2 = (0, 0, 0)

        actuator.joint = env_obj.world.CreatePrismaticJoint(
            bodyA=env_obj.exterior_box,
            bodyB=actuator,
            anchor=actuator.position,
            axis=(0, 1),
            lowerTranslation=0,
            upperTranslation=ACTUATOR_TRANSLATION_MAX,
            enableLimit=True,
            maxMotorForce=10000.0,
            motorSpeed=0,
            enableMotor=True)

        env_obj.actuator_list.append(actuator)

    env_obj.drawlist = env_obj.actuator_list

    # Creating the linkages that will form the semi-flexible membrane
    link_fixture = b2FixtureDef(
        shape=b2PolygonShape(box=(LINK_WIDTH / 2, LINK_HEIGHT / 2)),
        density=1,
        friction=0.6,
        restitution=0.0,
        groupIndex=-1  # neg index to prevent collision
    )

    for i in range(4):
        link_left = env_obj.world.CreateDynamicBody(
            position=(BOX_SIDE_OFFSET + (GAP * i + LINK_WIDTH / 2), 0),
            fixtures=link_fixture)
        link_left.color1 = (0, 1, 1)
        link_left.color2 = (1, 0, 1)
        env_obj.link_left_list.append(link_left)
        link_right = env_obj.world.CreateDynamicBody(
            position=(BOX_SIDE_OFFSET + (GAP * (i + 1) - LINK_WIDTH / 2), 0),
            fixtures=link_fixture)
        link_right.color1 = (0, 1, 1)
        link_right.color2 = (1, 0, 1)
        env_obj.link_right_list.append(link_right)

        joint_left = env_obj.world.CreateRevoluteJoint(
            bodyA=env_obj.actuator_list[i],
            bodyB=link_left,
            anchor=env_obj.actuator_list[i].worldCenter,
            collideConnected=False)

        joint_right = env_obj.world.CreateRevoluteJoint(
            bodyA=env_obj.actuator_list[i + 1],
            bodyB=link_right,
            anchor=env_obj.actuator_list[i + 1].worldCenter,
            collideConnected=False)

        joint_middle = env_obj.world.CreatePrismaticJoint(
            bodyA=link_left,
            bodyB=link_right,
            anchor=(link_right.position.x - (LINK_WIDTH / 2 + LINK_HEIGHT / 2),
                    (link_left.position.y + link_right.position.y) / 2.0),
            axis=(1, 0),
            lowerTranslation=0,
            upperTranslation=UPPER_TRANSLATION_MIDDLE_JOINT,
            enableLimit=True)
    # Adding linkages to the drawlist
    env_obj.drawlist = env_obj.link_left_list + env_obj.link_right_list + env_obj.drawlist
Ejemplo n.º 50
0
 def __init__(self, world, position, radius=3, type='kinematic'):
     if type == 'kinematic':
         self.robot = world.CreateKinematicBody(
             position=position,
             shapes=[b2CircleShape(pos=position, radius=radius)])
Ejemplo n.º 51
0
 def __init__(self, world, position, radius):
     self.static_goal = world.CreateStaticBody(
         position=position,
         shapes=[b2CircleShape(pos=position,
                               radius=radius)]  #change this to circles
     )
Ejemplo n.º 52
0
    def __init__(self):
        super(GP, self).__init__()

        self.primitive_set = {
            'L': self.create_arm,
            'E': self.create_endpoint,
            'S': self.create_split,
            'W': self.create_wheel
        }

        self.creatures = []
        self.simulation_time = 0
        self.generation = 0
        self.best_fitness = 0
        self.fitnesses = []
        self.average_complexity = 0
        self.complexities = []
        self.average_depth = 0
        self.depths = []

        self.fitness_file = 'fitness.csv'
        self.complexity_file = 'complexities.csv'
        self.depth_file = 'depths.csv'

        # The ground
        ground = self.world.CreateStaticBody(shapes=[
            b2EdgeShape(vertices=[(-1000, 0), (1000, 0)]),
        ])

        self.obstacle_count = 400

        # Pre-defined obstacle types
        self.box = b2FixtureDef(
            shape=b2PolygonShape(box=(0.6, 0.6)),  #large
            density=1,
            friction=0.3)
        self.circle = b2FixtureDef(
            shape=b2CircleShape(radius=0.2),  #small
            density=1)
        self.triangle = b2FixtureDef(
            shape=b2PolygonShape(vertices=[(0, -0.5), (1,
                                                       2.2), (2,
                                                              -0.5)]),  #middle
            density=1)

        # Randomly generated obstacle shapes and distances
        obstacle_set = [self.box, self.circle, self.triangle]
        self.obstacles = []
        for i in np.random.uniform(-50, 1000, self.obstacle_count):
            obstacle = self.world.CreateStaticBody(
                fixtures=random.choice(obstacle_set), position=(i, 0.5))
            self.obstacles.append(obstacle)

        # Create initial population
        for i in range(self.population_size):
            self.creatures.append(self.create_prototype())

        with open(self.fitness_file, 'w', newline='') as f:
            wr = csv.writer(f)
            wr.writerow(['generation', 'best fitness'])

        with open(self.complexity_file, 'w', newline='') as f:
            wr = csv.writer(f)
            wr.writerow(['generation', 'average complexity'])

        with open(self.depth_file, 'w', newline='') as f:
            wr = csv.writer(f)
            wr.writerow(['generation', 'average depth'])
Ejemplo n.º 53
0
    def __init__(self):
        super(Membrane, self).__init__()

        # Creating the Exterior Box that defines the 2D Plane
        self.exterior_box = self.world.CreateStaticBody(
            position=(0, 0), shapes=b2LoopShape(vertices=EXT_BOX_POLY))

        # Creating the object to manipulate
        ball_fixture = b2FixtureDef(shape=b2CircleShape(radius=BOX_WIDTH / 40),
                                    density=1,
                                    friction=0.6)

        self.ball = self.world.CreateDynamicBody(position=(BOX_WIDTH / 2,
                                                           BOX_HEIGHT / 2),
                                                 fixtures=ball_fixture)

        # Creating 5 actuators
        self.actuator_list = []
        self.actuator_joint_list = []

        actuator_fixture = b2FixtureDef(shape=b2CircleShape(radius=BOX_WIDTH /
                                                            50.0),
                                        density=1,
                                        friction=0.6,
                                        groupIndex=-1)

        for i in range(5):
            actuator = self.world.CreateDynamicBody(
                position=(BOX_WIDTH / 5 * i + BOX_WIDTH / 10, BOX_HEIGHT / 10),
                fixtures=actuator_fixture)

            # actuator = self.world.CreateKinematicBody(
            #     position = (BOX_WIDTH/5*i+BOX_WIDTH/10, BOX_HEIGHT/10),
            #     shapes = b2CircleShape(radius=BOX_WIDTH/50.0), # diameter is 1/5th of the space allocated for each actuator
            #     )

            actuator_joint = self.world.CreatePrismaticJoint(
                bodyA=self.exterior_box,
                bodyB=actuator,
                anchor=actuator.position,
                axis=(0, 1),
                lowerTranslation=0,
                upperTranslation=BOX_WIDTH * 5.0 / 6.0,
                enableLimit=True,
                maxMotorForce=1000.0,
                motorSpeed=0,
                enableMotor=True)

            self.actuator_list.append(actuator)
            self.actuator_joint_list.append(actuator_joint)

        self.actuator_joint_list[0].motorSpeed = 1.0
        self.actuator_joint_list[3].motorSpeed = 0.5
        self.actuator_joint_list[2].motorSpeed = 0.1

        # Creating the linkages that will form the semi-flexible membrane
        self.link_left_list = []  # four links
        self.link_right_list = []  # four links

        link_fixture = b2FixtureDef(
            shape=b2PolygonShape(box=(BOX_WIDTH / 12, BOX_WIDTH / 70.0)),
            density=1,
            friction=0.6,
            groupIndex=-1  # neg index to prevent collision
        )

        for i in range(1, 5):
            link_left = self.world.CreateDynamicBody(
                position=(BOX_WIDTH / 5 * i - BOX_WIDTH / 10 + BOX_WIDTH / 12,
                          BOX_HEIGHT / 10),
                fixtures=link_fixture)
            self.link_left_list.append(link_left)

            link_right = self.world.CreateDynamicBody(
                position=(BOX_WIDTH / 5 * i + BOX_WIDTH / 10 - BOX_WIDTH / 12,
                          BOX_HEIGHT / 10),
                fixtures=link_fixture)
            self.link_right_list.append(link_right)

            joint_left = self.world.CreateRevoluteJoint(
                bodyA=self.actuator_list[i - 1],
                bodyB=link_left,
                anchor=self.actuator_list[i - 1].worldCenter,
                collideConnected=False)

            joint_right = self.world.CreateRevoluteJoint(
                bodyA=self.actuator_list[i],
                bodyB=link_right,
                anchor=self.actuator_list[i].worldCenter,
                collideConnected=False)

            joint_middle = self.world.CreatePrismaticJoint(
                bodyA=link_left,
                bodyB=link_right,
                anchor=(link_right.position.x - BOX_WIDTH / 12 +
                        BOX_WIDTH / 70, link_right.position.y),
                axis=(1, 0),
                lowerTranslation=0,
                upperTranslation=BOX_WIDTH / 6 - BOX_WIDTH / 35,
                enableLimit=True)
Ejemplo n.º 54
0
    def __init__(self):
        super(CollisionProcessing, self).__init__()

        # Tell the framework we're going to use contacts, so keep track of them
        # every Step.
        self.using_contacts = True

        # Ground body
        world = self.world
        ground = world.CreateBody(
            shapes=b2EdgeShape(vertices=[(-50, 0), (50, 0)],)
        )

        xlow, xhi = -5, 5
        ylow, yhi = 2, 35
        random_vector = lambda: b2Vec2(
            b2Random(xlow, xhi), b2Random(ylow, yhi))

        # Small triangle
        triangle = b2FixtureDef(
            shape=b2PolygonShape(vertices=[(-1, 0), (1, 0), (0, 2)]),
            density=1,
        )

        world.CreateBody(
            type=b2_dynamicBody,
            position=random_vector(),
            fixtures=triangle,
        )

        # Large triangle (recycle definitions)
        triangle.shape.vertices = [
            2.0 * b2Vec2(v) for v in triangle.shape.vertices]

        tri_body = world.CreateBody(type=b2_dynamicBody,
                                    position=random_vector(),
                                    fixtures=triangle,
                                    fixedRotation=True,  # <--
                                    )
        # note that the large triangle will not rotate

        # Small box
        box = b2FixtureDef(
            shape=b2PolygonShape(box=(1, 0.5)),
            density=1,
            restitution=0.1,
        )

        world.CreateBody(
            type=b2_dynamicBody,
            position=random_vector(),
            fixtures=box,
        )

        # Large box
        box.shape.box = (2, 1)
        world.CreateBody(
            type=b2_dynamicBody,
            position=random_vector(),
            fixtures=box,
        )

        # Small circle
        circle = b2FixtureDef(
            shape=b2CircleShape(radius=1),
            density=1,
        )

        world.CreateBody(
            type=b2_dynamicBody,
            position=random_vector(),
            fixtures=circle,
        )

        # Large circle
        circle.shape.radius *= 2
        world.CreateBody(
            type=b2_dynamicBody,
            position=random_vector(),
            fixtures=circle,
        )