Esempio n. 1
0
    def __init__(self, parent, position, walking_task):
        self.walking_task = walking_task
        (w, l) = walking_task.leg_length / 5.0, walking_task.leg_length
        mass = w * l * 0.2
        # Upper leg
        upperleg = pymunk.Body(mass, pymunk.moment_for_box(mass, w, l))
        upperleg.position = pymunk.Vec2d(parent.position) + pymunk.Vec2d(position) + pymunk.Vec2d(0, l/2.0 - w/2.0)
        shape = pymunk.Poly.create_box(upperleg, (w,l))
        shape.group = 1
        shape.friction = 2.0
        # Joints
        pos = pymunk.Vec2d(parent.position) + pymunk.Vec2d(position)
        hip = Joint(parent, upperleg, pos, (-0.1*pi, 0.9*pi), self.walking_task.max_rate)
        walking_task.space.add(hip.pivot, hip.motor, hip.limit, upperleg, shape)

        # Lower leg
        lowerleg = pymunk.Body(mass, pymunk.moment_for_box(mass, w, l * 1.2))
        lowerleg.position = pymunk.Vec2d(upperleg.position) + pymunk.Vec2d(0, l - w/2.0)
        shape = pymunk.Poly.create_box(lowerleg, (w, l * 1.2))
        shape.group = 1
        shape.friction = 2.0
        # Joints
        pos =  pymunk.Vec2d(upperleg.position) + pymunk.Vec2d(0, l/2.0 - w/2.0)
        knee = Joint(upperleg, lowerleg, pos, (-0.9*pi, 0.1*pi), self.walking_task.max_rate)
        walking_task.space.add(knee.pivot, knee.motor, knee.limit, lowerleg, shape)
        
        self.upperleg = upperleg
        self.lowerleg = lowerleg
        self.hip = hip
        self.knee = knee
Esempio n. 2
0
 def __init__(self, name, width = 0, height = 0, oType = 'loi'):
      
    self.name = name
    self.type = oType
       
    if width == 0 or height == 0:
       mass       = 1
       radius     = 0.5
       inertia    = pymunk.moment_for_circle(mass, 0, radius)
       self.body  = pymunk.Body(mass, inertia)
       self.shape = pymunk.Circle(self.body, radius)
          
       self.dim   = (1,1)
    else:
       mass       = 1
       radius     = 0.5
       inertia   = pymunk.moment_for_box(mass, width, height)
       self.body  = pymunk.Body(mass, inertia)
       verts = [(-width/2,-height/2), (width/2,-height/2),
                 (width/2, height/2), (-width/2,height/2)]
       self.shape = pymunk.Poly(self.body,verts)
       self.shape.friction = 0.01
       self.shape.elasticity = 0.0
          
       self.dim   = (width,height)
Esempio n. 3
0
    def __init__(self, world, position, width=1.6, length=4.0, tire_width=.25, tire_length=.8, skidmarks=None, body_density=1.0):
        mass = width * length * body_density
        inertia = moment_for_box(mass, width, length)
        self.world = world
        body = Body(mass, inertia, )
        body.position = position
        shape = Poly.create_box(body, size=(width, length))
        super(Car, self).__init__(world, body, shape)

        slot_density = .01
        slot_radius = .1
        slot_mass = slot_density * (slot_radius ** 2) * pi
        slot_inertia = moment_for_circle(slot_mass, 0.0, slot_radius)
        #self.slot = Body(slot_mass, slot_inertia)


        flpos = position[0] - width / 2.0 - tire_width * 2, position[1] + length / 2.0
        self.front_left = Tire(self, flpos, tire_width, tire_length, skidmarks=skidmarks, powered=False, density=body_density)


        frpos = position[0] + width / 2.0 + tire_width * 2, position[1] + length / 2.0
        self.front_right = Tire(self, frpos, tire_width, tire_length, skidmarks=skidmarks, powered=False, density=body_density)
        
        rlpos = position[0] - width / 2.0 - tire_width * 2, position[1] - length / 2.0
        self.rear_left = Tire(self, rlpos, tire_width * 1.5, tire_length, steerable=False, skidmarks=skidmarks, density=body_density)

        rrpos = position[0] + width / 2.0 + tire_width * 2, position[1] - length / 2.0
        self.rear_right = Tire(self, rrpos, tire_width * 1.5, tire_length, steerable=False, skidmarks=skidmarks, density=body_density)
        self.tires = [self.front_left, self.front_right, self.rear_left, self.rear_right]
Esempio n. 4
0
    def handle_hanging(self, shape):
        logger.info('loading hanging %s', shape)
        # assert(not shape.body.is_static)

        shape.cache_bb()
        bb = shape.bb
        rect = pygame.Rect((bb.left, bb.top,
                            bb.right - bb.left, bb.top - bb.bottom))
        rect.normalize()

        shape.layers = 3
        shape.collision_type = 0
        # shape.body.velocity_func = ignore_gravity
        shape.body.mass = 1
        shape.body.moment = pymunk.moment_for_box(1, rect.width, rect.height)

        anchor1 = shape.body.position - (0, 0)
        joint = pymunk.PivotJoint(self.space.static_body, shape.body, anchor1,
                                  (0, 0))

        self.space.add(joint)

        s = pygame.Surface((rect.width, rect.height))
        s.fill((255, 255, 255))

        spr = sprite.BoxSprite(shape)
        spr.original_surface = resources.images['hanging']
        m = models.BasicModel()
        m.sprite = spr
Esempio n. 5
0
    def __init__(self, space, field_friction, field_observation, initial_pos,
                       size=8, 
                       motor_torque=6,
                       friction_scale=0.2,
                       angular_damping=0.9,
                       force_global=False):
        self.field_friction = field_friction
        self.field_observation = field_observation
        self.size = size
        self.friction_scale = friction_scale
        self.motor_torque = motor_torque
        self.angular_damping = angular_damping
        self.force_global = force_global
        
        mass = size ** 2 * 0.2
        self.body = body = pymunk.Body(mass, pymunk.moment_for_box(mass, size, size))
        body.position = pymunk.Vec2d(initial_pos[0], initial_pos[1])
        body.angle = initial_pos[2]
        self.shape = shape = pymunk.Poly.create_box(body, (size, size))
        shape.group = 1
        shape.collision_type = 1
        space.add(body, shape)
        
        self.sensors = [(r, theta) for r in np.linspace(1,4,3) * size * 0.75
                                   for theta in np.linspace(-0.5 * np.pi, 0.5 * np.pi, 5)]

        self.l = self.r = 0
Esempio n. 6
0
 def _createPhysicsObject(self):
     """Return a new physics object"""
     if self.geometry_type == 'circle':
         inertia = pymunk.moment_for_circle(self.mass, 0, self.radius, (0,0))
     else:
         inertia = pymunk.moment_for_box(self.mass, self.width, self.height)
     #
     body = pymunk.Body(self.mass, inertia)
     body.velocity = self.velocity
     body.force = self.force
     #
     if self.geometry_type == 'circle':
         shape = pymunk.Circle(body, self.radius, (0,0))
     else:
         #shape = pymunk.Poly(body, [(0, 0), (self.width, 0), 
         #                           (self.width, self.height), (0, self.height)])
         w2, h2 = self.width/2, self.height/2
         shape = pymunk.Poly(body, [(-w2,-h2), (+w2, -h2), (+w2, +h2), (-w2, +h2)])
     #
     shape.elasticity = self.elasticity
     shape.collision_type = 2
     shape.group = self.group
     shape.layers = self.layers
     shape.friction = self.friction
     self.shape = shape
     self.body = body
Esempio n. 7
0
File: main.py Progetto: viblo/pymunk
    def car(self, space):
        pos = Vec2d(100,100)

        wheel_color = .2,.86,.47
        shovel_color = .86,.47,.2
        mass = 100
        radius = 25
        moment = pymunk.moment_for_circle(mass, 20, radius)
        wheel1_b = pymunk.Body(mass, moment)
        wheel1_s = pymunk.Circle(wheel1_b, radius)
        wheel1_s.friction = 1.5
        wheel1_s.color = wheel_color
        space.add(wheel1_b, wheel1_s)

        mass = 100
        radius = 25
        moment = pymunk.moment_for_circle(mass, 20, radius)
        wheel2_b = pymunk.Body(mass, moment)
        wheel2_s = pymunk.Circle(wheel2_b, radius)
        wheel2_s.friction = 1.5
        wheel2_s.color = wheel_color
        space.add(wheel2_b, wheel2_s)

        mass = 100
        size = (50,30)
        moment = pymunk.moment_for_box(mass, size)
        chassi_b = pymunk.Body(mass, moment)
        chassi_s = pymunk.Poly.create_box(chassi_b, size)
        space.add(chassi_b, chassi_s)

        vs = [(0,0),(0,-45),(25,-45)]
        shovel_s = pymunk.Poly(chassi_b, vs, transform = pymunk.Transform(tx=85))
        shovel_s.friction = 0.5
        shovel_s.color = shovel_color
        space.add(shovel_s)

        wheel1_b.position = pos - (55,0)
        wheel2_b.position = pos + (55,0)
        chassi_b.position = pos + (0,25)

        space.add(
            pymunk.PinJoint(wheel1_b, chassi_b, (0,0), (-25,-15)),
            pymunk.PinJoint(wheel1_b, chassi_b, (0,0), (-25, 15)),
            pymunk.PinJoint(wheel2_b, chassi_b, (0,0), (25,-15)),
            pymunk.PinJoint(wheel2_b, chassi_b, (0,0), (25, 15))
            )
        
        speed = -4
        space.add(
            pymunk.SimpleMotor(wheel1_b, chassi_b, speed),
            pymunk.SimpleMotor(wheel2_b, chassi_b, speed)
        )
        with self.canvas:
            Color(*wheel_color)
            wheel1_s.ky = self.ellipse_from_circle(wheel1_s)
            Color(*wheel_color)
            wheel2_s.ky = self.ellipse_from_circle(wheel2_s)
            Color(*shovel_color)
            chassi_s.ky = Quad(points=self.points_from_poly(chassi_s))
            shovel_s.ky = Triangle(points=self.points_from_poly(shovel_s))
Esempio n. 8
0
    def __init__(self, gun_type="pistol"):
        from time import time
        # set gun attributes

        attrs = self._gun_types[gun_type]
        l = self.length = attrs["length"]
        t = self.thickness = attrs["thickness"]
        m = self.mass = attrs["mass"]
        mo = self.moment = pymunk.moment_for_box(m, l, t)
        f = self.force = attrs["force"]
        h = self.handle = attrs["handle"]
        b = self.bullet = attrs["bullet"]
        c = self.cooldown = attrs["cooldown"]
        self.cooldown_timer = time()  # timer between shots
        self.cooldown_timer_end = self.cooldown_timer + self.cooldown

        # pygame init

        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface([l, t])
        self.rect = self.image.get_rect()

        # pymunk init

        self.body = pymunk.Body(m, mo)
        self.body_shape = pymunk.Poly(self.body, [(0,0), (0,-t), (l,-t), (l,0)])
        self.body_shape.color = pygame.color.THECOLORS["black"]
        self.body_shape.group = COLLISION_GROUP["character"]
        self.constraints = []
Esempio n. 9
0
 def addBox(self, actorID, **kwargs):
     '''Create a box shape and body'''
     if kwargs['moment'] == -1:
         kwargs['moment'] = pymunk.moment_for_box(kwargs['mass'], kwargs['size'][0], kwargs['size'][1])
         
     body = self.createBody(kwargs['isStatic'], kwargs['mass'], kwargs['moment'], kwargs['pos'])
     shape = pymunk.Poly.create_box(body, kwargs['size'])
     self.addShape(actorID, body, shape, kwargs['elasticity'], kwargs['collisionType'])
Esempio n. 10
0
	def __init__(self, space, name, initpos):
		self.name = name
		self.space = space
		self.body = munk.Body(Block.MASS, munk.moment_for_box(Block.MASS, Block.WIDTH, Block.WIDTH))
		w2 = Block.WIDTH / 2
		self.verts = [(-w2, -w2), (-w2, w2), (w2, w2), (w2, -w2)]
		self.shape = munk.Poly(self.body, self.verts)
		self.space.add(self.body, self.shape)
		self.body.position = initpos
Esempio n. 11
0
 def __init__(self, space, pos, size):
     self.points = []
     self.points.append(tuple(pos))
     self.points.append((pos[0], pos[1] + size[1]))
     self.points.append((pos[0]+ size[0], pos[1]+size[1]))
     self.points.append((pos[0]+ size[0], pos[1]))
     inertia = pymunk.moment_for_box(1, size[0], size[1])
     pymunk.Body.__init__(self, 1, inertia)
     self.shape = pymunk.Poly(self, self.points, util.vectorMult(size, -0.5))
     space.add(self, self.shape)
Esempio n. 12
0
 def testGeneral(self):
     p.version
     p.inf
     p.chipmunk_version
     
     m = p.moment_for_box(1, 2, 3)
     self.assertAlmostEqual(m, 1.08333333333)
     
     m = p.moment_for_segment(1, Vec2d(-1,0), Vec2d(1,0))
     self.assertAlmostEqual(m, 0.33333333333)
Esempio n. 13
0
 def add_box(self, mass=1):
     radius = 24
     inertia = pymunk.moment_for_box(mass, 0, radius)
     body = pymunk.Body(mass, inertia)
     x = random.randint(20,600)
     y = random.randint(20,400)
     body.position = x, y
     shape = PymunkShape.square(body, radius)
     self.space.add(body, shape)
     return shape
Esempio n. 14
0
def box(space):
    global box_y
    
    mass = 10
    moment = pymunk.moment_for_box(mass, (40,20))
    b = pymunk.Body(mass, moment)
    s = pymunk.Poly.create_box(b, (40,20))
    s.friction = 1
    b.position = 600,box_y
    box_y -= 30
    space.add(b,s)
Esempio n. 15
0
    def __init__(self, space, position, size, hinge_pos, 
                 padding, 
                 ang_vel, start, end, 
                 image):
        self.padding = padding
        padding_left = self.padding[0]
        padding_bottom = self.padding[1]
        padding_right = self.padding[2]
        padding_top = self.padding[3]
        self.ang_vel = abs(ang_vel) # Refrain from using negative angular velocities, as it may give unexpected results.
        self.start = start + 57
        self.end = end + 57
        self.size = size
        #self.force = force
        self.space = space
        mass = 3
        self.inertia = pymunk.moment_for_box(mass, size[0], size[1])
        self.body = pymunk.Body(mass, self.inertia)
        self.body.angle = math.radians(start)
        self.body.position = (position[0]-hinge_pos[0], position[1]-hinge_pos[1])
        self.shape = pymunk.Poly.create_box(self.body, size)
        self.shape.friction = 1
        self.shape.group = 2
        self.space.add(self.body, self.shape)

        self.hinge_body = pymunk.Body()
        self.hinge_body.angle = math.radians(start) + math.radians(57)
        self.hinge_body.position = self.body.position[0] + hinge_pos[0], self.body.position[1] + hinge_pos[1]

        pivot = pymunk.constraint.PivotJoint(self.body, self.hinge_body, (hinge_pos), (0,0))
        self.space.add(pivot)

        gear = pymunk.constraint.GearJoint(self.body, self.hinge_body, 1.0, 1.0)
        self.space.add(gear)

        self.left = (position[0] - padding_left, position[1] + padding_top)
        self.bottom = (position[0] - padding_left, position[1]- padding_bottom)
        self.right = (position[0] + padding_right, position[1]- padding_bottom)
        self.top = (position[0] + padding_right, position[1] + padding_top)

        self.bb = pymunk.BB(position[0] - padding_left, #- hinge_pos[0], # left
                            position[1] - padding_bottom, #  - hinge_pos[1], # bottom
                            position[0] + padding_right, # - hinge_pos[0], # right
                            position[1] + padding_top, ) # - hinge_pos[1]) # top
        alpha = 100
        self.color = (200,0,0,alpha)
        self.color2 = (0,200,0,alpha)
        self.color3 = (200,200,0,alpha)

        self.sprite = loaders.spriteloader(image,
                                           size = size,
                                           anchor = ('center','center'),
                                           linear_interpolation = True)
Esempio n. 16
0
    def testMomentHelpers(self):
        m = p.moment_for_circle(1,2,3,(1,2))
        self.assertAlmostEqual(m, 11.5)

        m = p.moment_for_segment(1, (-10,0), (10,0), 1)
        self.assertAlmostEqual(m, 40.6666666666)

        m = p.moment_for_poly(1, [(0,0), (10,10), (10,0)], (1,2), 3)
        self.assertAlmostEqual(m, 98.3333333333)

        m = p.moment_for_box(1, (2, 3))
        self.assertAlmostEqual(m, 1.08333333333)
Esempio n. 17
0
def car(space):
    pos = Vec2d(100,200)

    wheel_color = 52,219,119
    shovel_color = 219,119,52
    mass = 100
    radius = 25
    moment = pymunk.moment_for_circle(mass, 20, radius)
    wheel1_b = pymunk.Body(mass, moment)
    wheel1_s = pymunk.Circle(wheel1_b, radius)
    wheel1_s.friction = 1.5
    wheel1_s.color = wheel_color
    space.add(wheel1_b, wheel1_s)

    mass = 100
    radius = 25
    moment = pymunk.moment_for_circle(mass, 20, radius)
    wheel2_b = pymunk.Body(mass, moment)
    wheel2_s = pymunk.Circle(wheel2_b, radius)
    wheel2_s.friction = 1.5
    wheel2_s.color = wheel_color
    space.add(wheel2_b, wheel2_s)

    mass = 100
    size = (50,30)
    moment = pymunk.moment_for_box(mass, size)
    chassi_b = pymunk.Body(mass, moment)
    chassi_s = pymunk.Poly.create_box(chassi_b, size)
    space.add(chassi_b, chassi_s)

    vs = [(0,0),(25,45),(0,45)]
    shovel_s = pymunk.Poly(chassi_b, vs, transform = pymunk.Transform(tx=85))
    shovel_s.friction = 0.5
    shovel_s.color = shovel_color
    space.add(shovel_s)

    wheel1_b.position = pos - (55,0)
    wheel2_b.position = pos + (55,0)
    chassi_b.position = pos + (0,-25)

    space.add(
        pymunk.PinJoint(wheel1_b, chassi_b, (0,0), (-25,-15)),
        pymunk.PinJoint(wheel1_b, chassi_b, (0,0), (-25, 15)),
        pymunk.PinJoint(wheel2_b, chassi_b, (0,0), (25,-15)),
        pymunk.PinJoint(wheel2_b, chassi_b, (0,0), (25, 15))
        )
    
    speed = 4
    space.add(
        pymunk.SimpleMotor(wheel1_b, chassi_b, speed),
        pymunk.SimpleMotor(wheel2_b, chassi_b, speed)
    )
Esempio n. 18
0
File: main.py Progetto: viblo/pymunk
 def box(self, space):        
     mass = 10
     moment = pymunk.moment_for_box(mass, (40,20))
     b = pymunk.Body(mass, moment)
     s = pymunk.Poly.create_box(b, (40,20))
     s.friction = 1
     b.position = 600, self.box_y
     self.box_y += 30
     space.add(b,s)
     
     with self.canvas:
         Color(0.2,0.2,0.2)
         s.ky = Quad(points=self.points_from_poly(s))
Esempio n. 19
0
 def __init__(self, mass, size):
     super(Box, self).__init__()
     self.size = size
     inertia = pymunk.moment_for_box(mass, (size, size))
     self.body = pymunk.Body(mass, inertia)
     shape = pymunk.Poly.create_box(self.body, (size,size))
     shape.elasticity = 0.2
     shape.friction = 0.7
     space.add(self.body, shape)
     p = self.size / 2
     self.vertex_list = pyglet.graphics.vertex_list(4, ("v2f\static", (-p,p, p,p, p,-p, -p,-p)))
     
     self.forces = []
 def addPhysicsTo(self, actor):
     """Add physics of a polygon"""
     w, h = actor.width, actor.height
     #
     # Scale the polygon points
     actual_points = [(px * w - w / 2.0, py * h - h / 2.0) for px, py in self.points]
     if self.mass:
         self.body = pymunk.Body(self.mass, moment=pymunk.moment_for_box(self.mass, w, h))
     else:
         self.body = pymunk.Body()
     self.shape = pymunk.Poly(self.body, actual_points)
     #
     super(PolygonSpritePhysics, self).addPhysicsTo(actor)
Esempio n. 21
0
	def __init__(self, space, name, initpos):
		self.space = space
		self.name = name
		self.body = munk.Body(Splinter.MASS, munk.moment_for_box(Splinter.MASS, Splinter.LENGTH, Splinter.BASELINE))
		l2 = Splinter.LENGTH / 2
		b2 = Splinter.BASELINE / 2
		self.verts = [(-l2, -b2), (-l2, b2), (l2, b2), (l2, -b2)]
		self.shape = munk.Poly(self.body, self.verts)
		self.space.add(self.body, self.shape)
		self.body.position = initpos

		self.lrps = 0.
		self.rrps = 0.
Esempio n. 22
0
    def __init__(self, width, height):
        pyglet.window.Window.__init__(self, vsync=False)

        self.draw_options = pymunk.pyglet_util.DrawOptions()
        pyglet.clock.schedule_interval(self.update, 1 / 60.0)

        # -- Pymunk space
        self.space = pymunk.Space()
        self.space.gravity = (0.0, -900.0)

        # Create the floor
        body = pymunk.Body(body_type=pymunk.Body.STATIC)
        self.floor = pymunk.Segment(body, [0, 10], [SCREEN_WIDTH, 10], 0.0)
        self.floor.friction = 10
        self.space.add(self.floor)

        # Create the circle
        player_x = 300
        player_y = 300
        mass = 2
        radius = 25
        inertia = pymunk.moment_for_circle(mass, 0, radius, (0, 0))
        circle_body = pymunk.Body(mass, inertia)
        circle_body.position = pymunk.Vec2d(player_x, player_y)
        self.circle_shape = pymunk.Circle(circle_body, radius, pymunk.Vec2d(0, 0))
        self.circle_shape.friction = 1

        self.space.add(circle_body, self.circle_shape)

        # Create the box
        size = BOX_SIZE
        mass = 5
        moment = pymunk.moment_for_box(mass, (size, size))
        moment = pymunk.inf
        body = pymunk.Body(mass, moment)
        body.position = pymunk.Vec2d(player_x, player_y + 49)
        self.box_shape = pymunk.Poly.create_box(body, (size, size))
        self.box_shape.friction = 0.3
        self.space.add(body, self.box_shape)

        # Create a joint between them
        constraint = pymunk.constraint.PinJoint(self.box_shape.body, self.circle_shape.body, (-20, 0), (0, 0))
        self.space.add(constraint)

        constraint = pymunk.constraint.PinJoint(self.box_shape.body, self.circle_shape.body, (20, 0), (0, 0))
        self.space.add(constraint)

        # Make the circle rotate
        constraint = pymunk.constraint.SimpleMotor(self.circle_shape.body, self.box_shape.body, -3)
        self.space.add(constraint)
Esempio n. 23
0
 def add_rectangle(self, x, y, width, height, color=(1, 0, 0)):
     moment = cy.moment_for_box(100., width, height)
     body = cy.Body(100, moment)
     body.position = x, y
     box = cy.Poly.create_box(body, size=(width, height))
     box.elasticity = 0.
     self.space.add(box, body)
     widget = ScatterPlane(pos=(0., 0.), size=(width, height))
     with widget.canvas:
         Color(*color)
         rect = Rectangle(pos=(0, 0), size=(width, height))
         
     self.rects.append((body, widget, rect))
     self.add_widget(widget)
Esempio n. 24
0
 def create_entity(self, x, y, pos):
     entity = self.manager.create_entity()
     inertia = pm.moment_for_box(constants.PADDLE_MASS, x, y)
     body = pm.Body(constants.PADDLE_MASS, inertia)
     body.position.x = pos[0]
     body.position.y = pos[1]
     body.angular_velocity_limit = 0
     self.manager.add_component(entity, body)
     shape = pm.Poly.create_box(body, (x, y))
     shape.elasticity = 1.3
     shape.friction = 0
     shape.collision_type = constants.PADDLE_COLLISION_TYPE
     self.manager.add_component(entity, shape)
     self.space.add(body, shape)
     return entity
Esempio n. 25
0
 def __init__(self, space):
     mass = 20
     radius = 24
     self.width = radius * 5
     self.height = radius
     inertia = pymunk.moment_for_box(mass, 0, radius)
     body = pymunk.Body(mass, inertia)
     x = random.randint(20,600)
     y = random.randint(20,400)
     body.position = x, y
     shape = PymunkShape.rectangle(body, self.width, self.height)
     space.add(body, shape)
     self.shape = shape
     self.body = body
     self.jetoffset = (12, 12)
     self.jetspeed = 16
Esempio n. 26
0
 def __init__(self):
     # load images
     base_path = "images/blocks/{}.png".format(self.image)
     self.img = load_image(base_path, self.image_anchor)
     # create collision object
     w = h = BLOCK_SIZE
     inertia = pymunk.moment_for_box(1, w, h)
     self._body = pymunk.Body(1, inertia)
     self._body.position = Vec2d(0, 0)
     self._shape = pymunk.Poly.create_box(self._body, (w, h), radius=0.2)
     self._shape.collision_type = COLLISION_TYPES['ghost']
     self._shape.sensor = True
     self._shape._get_block = ref(self)
     SPACE.add(self._body, self._shape)
     # what can it connect to?
     self.valid_welds = []
Esempio n. 27
0
    def __init__(self, pos):
        super(Block, self).__init__()

        #Import the block image.
        self.block_img = cocos.sprite.Sprite('brick.png')

        #Pymunk physics variables.
        self.verts = [(-15, -15), (-15, 15), (15, 15), (15, -15)]
        self.mass = 0.1
        self.moment = pymunk.moment_for_box(self.mass, 32, 32)
        self.body = pymunk.Body(self.mass, self.moment)
        self.body.position = pos
        self.shape = pymunk.Poly(self.body, self.verts)
        self.shape.layers = 1
        self.shape.collision_type = 4
        self.shape.friction = 1
Esempio n. 28
0
def load_box(tmxobject, map_height, static_body, defaults):
    """
    Creates a pymunk.Poly in the shape of a box from a TiledObject instance and
    orients it relative to the height of a TiledMap.

    :param TiledObject tmxobject: A TiledObject instance that represents a box.
    :param int map_height: The height of the TiledMap that the TiledObject \
    was loaded from in pixels.

    :rtype: pymunk.Poly
    :return: A pymunk.Poly shape instance.
    """
    box_defaults = defaults["pymunktmx_box"]
    shape_attrs = get_shape_attrs(tmxobject, box_defaults)
    body_attrs = get_body_attrs(tmxobject, box_defaults)
    offset = body_attrs[u"offset"]
    radius = shape_attrs[u"radius"]

    shape = None
    if body_attrs[u"static"]:
        tl = tmxobject.x, float(map_height) - tmxobject.y
        tr = tmxobject.x + tmxobject.width, tl[1]
        bl = tl[0], float(map_height) - (tmxobject.y + tmxobject.height)
        br = tr[0], bl[1]
        verts = [tl, bl, br, tr]
        shape = pymunk.Poly(static_body, verts, offset, radius)
    else:
        x = float(tmxobject.x)
        y = float(float(map_height) - tmxobject.y)
        mass = body_attrs[u"mass"]
        tl = 0.0, 0.0
        tr = float(tmxobject.width), 0.0
        bl = 0, -float(tmxobject.height)
        br = tr[0], bl[1]
        verts = [tl, bl, br, tr]
        moment = pymunk.moment_for_box(
            mass, tmxobject.height, tmxobject.width)
        body = pymunk.Body(mass, moment)
        body.position = (x, y)

        set_attrs(body_attrs, body,
                  skip_keys=[u"position", u"mass", u"static"])

        shape = pymunk.Poly(body, verts, offset, radius)

    set_attrs(shape_attrs, shape, skip_keys=[u"radius"])
    return [shape]
Esempio n. 29
0
    def __init__(self, 
            space, 
            collision_type = 0,
            group = 0,
            friction = pymunk.inf,
            mass = pymunk.inf,
            width = 0,
            height = 0,
            x = 0,
            y = 0,
            angle = 0,
            static = False, 
            *args, **kwargs):

        super(Entity, self).__init__(*args, **kwargs)

        # Physics setup
        self.space = space
        self._mass = mass
        self._moment = pymunk.moment_for_box(mass, width, height)

        # body
        body = pymunk.Body(self._mass, self._moment)
        body.position = x, y
        body.angle = angle

        # shape
        hw = width // 2
        hh = height // 2
        vs = [(-hw, hh), (hw, hh), (hw, -hh), (-hw, -hh)]
        shape = pymunk.Poly(body, vs)
        shape.friction = friction
        shape.collision_type = collision_type
        space.add(shape)

        self.pymunk_shape = shape
        self.pymunk_body = body
        if static: self._set_static()

        # force static state update if not static
        self._static = True
        self.static = static

        # allow access the the entity from the shape for body
        self.pymunk_body.entity = self
        self.pymunk_shape.entity = self
Esempio n. 30
0
    def __init__(self, run_path, space, screen):
        self.area = screen.get_rect()
        self.step = 1
        self.direction = utils.Direction.right
        #self.jumping = False
        self.walking = False

        inertia = pymunk.moment_for_box(self.MASS, self.WIDTH, self.HEIGHT)
        self.body = pymunk.Body(self.MASS, inertia)
        self.body.position = 100, FLOOR_Y
        vertices = [(0, 0), (self.WIDTH, 0), (self.WIDTH, self.HEIGHT), (0, self.HEIGHT)]
        shape = pymunk.Poly(self.body, vertices, offset=(0, 0))
        shape.friction = 0.55
        space.add(self.body, shape)

        self.rect = Rect(self.body.position.x, self.body.position.y, self.WIDTH, self.HEIGHT)
        AnimatedSprite.__init__(self, 'rabbit_sprite.png')  # call Sprite intializer
Esempio n. 31
0
    def __init__(self):
        self.ctx = ModernGL.create_context()
        ctx = self.ctx

        self.prog = ctx.program([
            ctx.vertex_shader('''
                #version 330

                uniform vec4 Camera;

                // Per vertex
                in vec2 in_vert;
                in vec2 in_texture;

                // Per instance
                in vec3 in_pos;
                in vec2 in_size;
                in vec4 in_tint;

                out vec2 v_vert;
                out vec2 v_texture;
                out vec4 v_tint;

                void main() {
                    mat2 rotate = mat2(
                        cos(in_pos.z), sin(in_pos.z),
                        -sin(in_pos.z), cos(in_pos.z)
                    );
                    v_vert = rotate * (in_vert * in_size) + in_pos.xy;
                    gl_Position = vec4((v_vert - Camera.xy) / Camera.zw, 0.0, 1.0);
                    v_texture = in_texture;
                    v_tint = in_tint;
                }
            '''),
            ctx.fragment_shader('''
                #version 330

                uniform sampler2D Texture;

                in vec2 v_vert;
                in vec2 v_texture;
                in vec4 v_tint;

                out vec4 f_color;

                void main() {
                    vec4 tex = texture(Texture, v_texture);
                    vec3 color = tex.rgb * (1.0 - v_tint.a) + v_tint.rgb * v_tint.a;
                    f_color = vec4(color, tex.a);
            }
            '''),
        ])

        img = Image.open('data/crate.png').convert('RGBA')
        self.tex1 = ctx.texture(img.size, 4, img.tobytes())
        self.tex1.use(0)

        img = Image.open('data/ball.png').convert('RGBA')
        self.tex2 = ctx.texture(img.size, 4, img.tobytes())
        self.tex2.use(1)

        vbo1 = ctx.buffer(
            struct.pack(
                '16f',
                -1.0,
                -1.0,
                0.0,
                0.0,
                -1.0,
                1.0,
                0.0,
                1.0,
                1.0,
                -1.0,
                1.0,
                0.0,
                1.0,
                1.0,
                1.0,
                1.0,
            ))

        self.vbo2 = ctx.buffer(reserve=1024 * 1024)

        vao_content = [
            (vbo1, '2f2f', ['in_vert', 'in_texture']),
            (self.vbo2, '3f2f4f/i', ['in_pos', 'in_size', 'in_tint']),
        ]

        self.vao = ctx.vertex_array(self.prog, vao_content)

        self.space = pymunk.Space()
        self.space.gravity = (0.0, -900.0)

        shape = pymunk.Segment(self.space.static_body, (5, 100), (595, 100),
                               1.0)
        shape.friction = 1.0
        self.space.add(shape)

        x = Vec2d(-270, 7.5) + (300, 100)
        y = Vec2d(0, 0)
        deltaX = Vec2d(0.5625, 1.1) * 20
        deltaY = Vec2d(1.125, 0.0) * 20

        self.bodies = []
        self.balls = []

        for x in range(5):
            for y in range(10):
                size = 20
                mass = 10.0
                moment = pymunk.moment_for_box(mass, (size, size))
                body = pymunk.Body(mass, moment)
                body.position = Vec2d(300 + x * 50, 105 + y * (size + .1))
                shape = pymunk.Poly.create_box(body, (size, size))
                shape.friction = 0.3
                self.space.add(body, shape)
                self.bodies.append(body)
Esempio n. 32
0
    def __init__(self, width, height, title):
        super().__init__(width, height, title)

        # Set the working directory (where we expect to find files) to the same
        # directory this .py file is in. You can leave this out of your own
        # code, but it is needed to easily run the examples using "python -m"
        # as mentioned at the top of this program.
        file_path = os.path.dirname(os.path.abspath(__file__))
        os.chdir(file_path)

        arcade.set_background_color(arcade.color.DARK_SLATE_GRAY)

        # -- Pymunk
        self.space = pymunk.Space()
        self.space.iterations = 35
        self.space.gravity = (0.0, -900.0)

        # Lists of sprites or lines
        self.sprite_list: arcade.SpriteList[PhysicsSprite] = arcade.SpriteList(
        )
        self.static_lines = []

        # Used for dragging shapes around with the mouse
        self.shape_being_dragged = None
        self.last_mouse_position = 0, 0

        self.draw_time = 0
        self.processing_time = 0

        # Create the floor
        floor_height = 80
        body = pymunk.Body(body_type=pymunk.Body.STATIC)
        shape = pymunk.Segment(body, [0, floor_height],
                               [SCREEN_WIDTH, floor_height], 0.0)
        shape.friction = 0.2
        shape.elasticity = 0.7
        self.space.add(shape)
        self.static_lines.append(shape)

        # Create the stacks of boxes
        for row in range(10):
            for column in range(10):
                size = 32
                mass = 1.0
                x = 500 + column * 32
                y = (floor_height + size / 2) + row * size
                moment = pymunk.moment_for_box(mass, (size, size))
                body = pymunk.Body(mass, moment)
                body.position = pymunk.Vec2d(x, y)
                shape = pymunk.Poly.create_box(body, (size, size))
                shape.elasticity = 0.7
                shape.friction = 0.2
                self.space.add(body, shape)
                # body.sleep()

                sprite = BoxSprite(
                    shape,
                    ":resources:images/tiles/boxCrate_double.png",
                    width=size,
                    height=size)
                self.sprite_list.append(sprite)
Esempio n. 33
0
    def evaluate(self, network, draw=False):
        """ Evaluate the efficiency of the given network. Returns the
            distance that the walker ran in the given time (max_steps).
        """
        if not isinstance(network, NeuralNetwork):
            network = NeuralNetwork(network)

        if draw:
            import pygame
            pygame.init()
            screen = pygame.display.set_mode((self.track_length, 200))
            pygame.display.set_caption("Simulation")
            clock = pygame.time.Clock()
            running = True
            font = pygame.font.Font(pygame.font.get_default_font(), 8)

        # Initialize pymunk
        self.space = space = pymunk.Space()
        space.gravity = (0.0, 900.0)
        space.damping = 0.7
        self.touching_floor = False
        # Create objects
        # Floor

        floor = pymunk.Body()
        floor.position = pymunk.Vec2d(self.track_length / 2.0, 210)
        sfloor = pymunk.Poly.create_box(floor, (self.track_length, 40))
        sfloor.friction = 1.0
        sfloor.collision_type = 1
        space.add_static(sfloor)

        # Torso
        torsolength = 20 + (self.num_legs // 2 - 1) * self.leg_spacing
        mass = torsolength * self.torso_height * self.torso_density
        torso = pymunk.Body(
            mass, pymunk.moment_for_box(mass, torsolength, self.torso_height))
        torso.position = pymunk.Vec2d(
            200, 200 - self.leg_length * 2 - self.torso_height)
        storso = pymunk.Poly.create_box(torso,
                                        (torsolength, self.torso_height))
        storso.group = 1
        storso.collision_type = 1
        storso.friction = 2.0
        # space.add_static(storso)
        space.add(torso, storso)

        # Legs
        legs = []
        for i in range(self.num_legs // 2):
            x = 10 - torsolength / 2.0 + i * self.leg_spacing
            y = self.torso_height / 2.0 - 10
            legs.append(Leg(torso, (x, y), self))
            legs.append(Leg(torso, (x, y), self))

        # Collision callback
        def oncollide(space, arb):
            self.touching_floor = True

        space.add_collision_handler(1, 1, post_solve=oncollide)

        for step in range(self.max_steps):

            # Query network
            input_width = max(len(legs), 4)
            net_input = np.zeros((3, input_width))
            torso_y = torso.position.y
            torso_a = torso.angle
            sine = np.sin(step / 10.0)
            hip_angles = [leg.hip.angle() for leg in legs]
            knee_angles = [leg.knee.angle() for leg in legs]
            other = [torso_y, torso_a, sine, 1.0]
            # Build a 2d input grid,
            # as in Clune 2009 Evolving Quadruped Gaits, p4
            net_input[0, :len(legs)] = hip_angles
            net_input[1, :len(legs)] = knee_angles
            net_input[2, :4] = other
            act = network.feed(net_input, add_bias=False)

            output = np.clip(act[-self.num_legs * 2:] * self.max_rate, -1.0,
                             1.0) / 2.0 + 0.5

            for i, leg in enumerate(legs):
                leg.hip.set_target(output[i * 2])
                leg.knee.set_target(output[i * 2 + 1])

            # Advance simulation
            space.step(1 / 50.0)
            # Check for success/failure
            if torso.position.x < 0:
                break
            if torso.position.x > self.track_length - 50:
                break
            if self.touching_floor:
                break

            # Draw
            if draw:
                print(act)
                # Clear
                screen.fill((255, 255, 255))
                # Do all drawing
                txt = font.render('%d' % step, False, (0, 0, 0))
                screen.blit(txt, (0, 0))
                # Draw objects
                for o in space.shapes + space.static_shapes:
                    if isinstance(o, pymunk.Circle):
                        pygame.draw.circle(
                            screen, (0, 0, 0),
                            (int(o.body.position.x), int(o.body.position.y)),
                            int(o.radius))
                    else:
                        pygame.draw.lines(screen, (0, 0, 0), True,
                                          [(int(p.x), int(p.y))
                                           for p in o.get_points()])
                # Flip buffers
                pygame.display.flip()
                clock.tick(50)

        if draw:
            pygame.quit()

        distance = torso.position.x
        # print "Travelled %.2f in %d steps." % (distance, step)
        return {'fitness': distance}
Esempio n. 34
0
    def __init__(self,
                 body_type=BODY_TYPE_DYNAMIC,
                 mass=1,
                 width=10,
                 height=10,
                 center_of_grav=None,
                 corner_radius=0,
                 transform=None,
                 rotation_lock=False,
                 rotation=(0, 0),
                 density=None,
                 friction=None,
                 elasticity=None,
                 color=None,
                 scene=None,
                 resource_ref_name=None,
                 prefix=None):
        self.corner_radius = corner_radius * .75
        QtGui.QGraphicsRectItem.__init__(self,
                                         0 - self.corner_radius,
                                         0 - self.corner_radius,
                                         width + self.corner_radius,
                                         height + self.corner_radius,
                                         scene=scene)
        #QtGui.QGraphicsRectItem.__init__(self,-width/2,-height/2,width/2,height/2,scene=scene)
        #self.graphic=QtGui.QGraphicsPixmapItem(QtGui.QPixmap('./resources/images/car_bod2.png','.png'),scene=scene)
        #self.graphic.setOffset(0,-40)

        self.__rotation_lock = rotation_lock
        self.__rotation_min, self.__rotation_max = rotation
        self.__color = [0, 0, 0, 255]
        self.__collison_box_visible = True
        self.__animator_visible = True

        bp.blueprint.__init__(self, prefix or 'ch_obj_box')
        self.__eventManager = bp.eventManager()
        self.eventManager = self.getEventManager

        inertia = pm.moment_for_box(mass, (width, height))
        self.chipBody = ChipBody(mass, inertia, body_type)

        pm.Poly.__init__(self,
                         self.chipBody,
                         self.__generate_coords(width, height),
                         transform=transform,
                         radius=corner_radius)

        self.cog = None
        if type(center_of_grav) == tuple:
            self.cog = pm.Vec2d(center_of_grav)
        else:
            self.cog = pm.Vec2d(self.center_of_gravity)
        self.cx, self.cy = self.cog

        if density:
            self.density = density
        if friction:
            self.friction = friction
        if elasticity:
            self.elasticity = elasticity

        if color:
            self.__color = color
            self.setBrushColor(color=color)
            self.setPenColor(color=color)
        else:
            self.setBrushColor(color=self.__color)
            self.setPenColor(color=self.__color)

        self.set_ref_name(resource_ref_name)
        self.add_self_to_catalog()

        self.animator = animationManager(self, scene)

        self.hide()
        self.animator.hide()
        self.updateChipObject()
Esempio n. 35
0
    def __init__(self,
                 filename,
                 center_x=0,
                 center_y=0,
                 scale=SPRITE_SCALING,
                 mass=DEFAULT_MASS * 2,
                 moment=None,
                 friction=PLAYER_FRICTION, # seeing if its better to use non-default value
                 body_type=pymunk.Body.DYNAMIC):

        super().__init__(filename, scale=scale, center_x=center_x, center_y=center_y)
        width = self.texture.width * scale
        height = self.texture.height * scale

        if moment is None:
            moment = pymunk.moment_for_box(mass, (width, height))

        self.body = pymunk.Body(mass, moment, body_type=body_type)
        self.body.position = pymunk.Vec2d(center_x, center_y)

        self.shape = pymunk.Poly.create_box(self.body, (width * 0.90, height * 0.90,), radius=0.8) # was 0.8
        self.shape.friction = friction
        self.shape.HITCOUNT = -100
        self.shape.name = "Player"
        self.punching = False

        self.set_hit_box([[-22, -60], [22, -60], [22, 50], [-22, 50]]) 
        # self._collision_radius = 0.5

        # Load in monkey textures
        try:
            self.textures = []
            # TEXTURE_LEFT
            texture = arcade.load_texture("./images/Char_Monkey_Free_Images/Animations/monkey_walk_1.png", mirrored=True)
            self.textures.append(texture)
            # TEXTURE_RIGHT
            texture = arcade.load_texture("./images/Char_Monkey_Free_Images/Animations/monkey_walk_1.png")
            self.textures.append(texture)
            texture = arcade.load_texture("./images/Char_Monkey_Free_Images/Animations/monkey_jump_4.png")
            self.textures.append(texture)
            texture = arcade.load_texture("./images/Char_Monkey_Free_Images/Animations/monkey_jump_4.png", mirrored=True)
            self.textures.append(texture)
            texture = arcade.load_texture("./images/Char_Monkey_Free_Images/Animations/monkey_armsup.png")
            self.textures.append(texture)
            texture = arcade.load_texture("./images/Char_Monkey_Free_Images/Animations/monkey_faceforward.png")
            self.textures.append(texture)
            texture = arcade.load_texture("./images/Char_Monkey_Free_Images/Animations/monkey_jump_swing_2.png", mirrored=True)
            self.textures.append(texture)
            texture = arcade.load_texture("./images/Char_Monkey_Free_Images/Animations/monkey_jump_swing_2.png")
            self.textures.append(texture)
            texture = arcade.load_texture("./images/Char_Monkey_Free_Images/Animations/monkey_armsup_happy.png")
            self.textures.append(texture)
            # TEXTURE_LEFT_2
            texture = arcade.load_texture("./images/Char_Monkey_Free_Images/Animations/monkey_walk_2.png", mirrored=True)
            self.textures.append(texture)
            # TEXTURE_RIGHT_2
            texture = arcade.load_texture("./images/Char_Monkey_Free_Images/Animations/monkey_walk_2.png")
            self.textures.append(texture)
            # TEXTURE_LEFT_3
            texture = arcade.load_texture("./images/Char_Monkey_Free_Images/Animations/monkey_walk_3.png", mirrored=True)
            self.textures.append(texture)
            # TEXTURE_RIGHT_3
            texture = arcade.load_texture("./images/Char_Monkey_Free_Images/Animations/monkey_walk_3.png")
            self.textures.append(texture)
            # TEXTURE_LEFT_4
            texture = arcade.load_texture("./images/Char_Monkey_Free_Images/Animations/monkey_walk_4.png", mirrored=True)
            self.textures.append(texture)
            # TEXTURE_RIGHT_4
            texture = arcade.load_texture("./images/Char_Monkey_Free_Images/Animations/monkey_walk_4.png")
            self.textures.append(texture)            

        except:
            logging.error("Unable to load textures")
            quit(1)

        self.scale = SPRITE_SCALING
Esempio n. 36
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((1000, 750))
    pygame.display.set_caption("KDC HW2 Parts 5 and 6")
    clock = pygame.time.Clock()

    space = pymunk.Space()
    space.gravity = (0.0, -2000.0)

    # add floor
    body = pymunk.Body(body_type=pymunk.Body.STATIC)
    body.position = (0, 100)
    floor = pymunk.Segment(body, (-1000, 100), (1000, 100), 1)
    floor.filter = pymunk.ShapeFilter(mask=pymunk.ShapeFilter.ALL_MASKS ^ 0x1)
    floor.friction = 1
    space.add(floor)

    # add cart
    cart_mass = 1
    cart_size = (200, 40)
    cart_moment = pymunk.moment_for_box(cart_mass, cart_size)
    cart_body = pymunk.Body(cart_mass, cart_moment)
    cart_body.position = (500, 300)
    cart_shape = pymunk.Poly.create_box(cart_body, cart_size)
    cart_shape.color = pygame.color.THECOLORS["red"]
    cart_shape.filter = pymunk.ShapeFilter(group=1)

    #add wheels
    wheel_mass = 0.5
    wheel_size = 20
    wheel_moment = pymunk.moment_for_circle(wheel_mass, 0, wheel_size)
    front_wheel_body = pymunk.Body(wheel_mass, wheel_moment)
    back_wheel_body = pymunk.Body(wheel_mass, wheel_moment)
    front_wheel_body.position = (575, 260)
    back_wheel_body.position = (425, 260)
    front_wheel_shape = pymunk.Circle(front_wheel_body, wheel_size)
    back_wheel_shape = pymunk.Circle(back_wheel_body, wheel_size)
    front_wheel_shape.friction = 1
    back_wheel_shape.friction = 1
    front_wheel_shape.color = pygame.color.THECOLORS["black"]
    back_wheel_shape.color = pygame.color.THECOLORS["black"]
    front_wheel_shape.filter = pymunk.ShapeFilter(group=1)
    back_wheel_shape.filter = pymunk.ShapeFilter(group=1)

    #add pole
    pole_mass = 0.1
    pole_size = (1, 200)
    pole_moment = pymunk.moment_for_box(pole_mass, pole_size)
    pole_body = pymunk.Body(pole_mass, pole_moment)
    pole_body.position = (500, 220)
    pole_shape = pymunk.Poly.create_box(pole_body, pole_size)
    pole_shape.color = pygame.color.THECOLORS["black"]
    pole_shape.filter = pymunk.ShapeFilter(categories=0x1, group=1)

    #create joints
    front_joint = pymunk.constraint.PivotJoint(front_wheel_body, cart_body,
                                               (575, 260))
    back_joint = pymunk.constraint.PivotJoint(back_wheel_body, cart_body,
                                              (425, 260))
    pole_joint = pymunk.constraint.PivotJoint(pole_body, cart_body, (500, 320))

    #add everything to the world
    space.add(cart_body, cart_shape, front_wheel_body, front_wheel_shape,
              back_wheel_body, back_wheel_shape, pole_body, pole_shape,
              front_joint, back_joint, pole_joint)

    draw_options = pymunk.pygame_util.DrawOptions(screen)

    ticks = 0

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit(0)
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                sys.exit(0)

        screen.fill((255, 255, 255))
        space.debug_draw(draw_options)
        space.step(1 / 50.0)
        pygame.display.flip()

        if ticks == 0:
            pole_body.apply_impulse_at_local_point((1, 0), (0, 0))

        # do control here
        p = (pole_body.position.x - cart_body.position.x)
        v = pole_body.velocity_at_local_point((0, 0)).x
        theta = pole_body.angle
        dtheta = pole_body.angular_velocity

        enerr = (0.0125 * (dtheta * dtheta)) - (0.4905 * (1 + math.cos(theta)))

        a = 7.5
        b = 0.25
        c = 7.5
        d = 1
        k = 20

        if theta > (math.pi - 0.5) and theta < (math.pi + 0.5):
            f = (a * p) + (b * v) + (c * (math.pi - theta)) + (d * dtheta)
        else:
            f = k * enerr * math.cos(theta) * dtheta

        cart_body.apply_impulse_at_local_point((f, 0), (0, 0))

        ticks += 1

        clock.tick(50)
Esempio n. 37
0
def create_rover(space, x, y):
    pos = Vec2d(x, y)

    wheel_color = 0, 0, 0

    # first wheel
    mass = 10
    radius = 25
    moment = pymunk.moment_for_circle(mass, 20, radius)
    wheel1_b = pymunk.Body(mass, moment)
    wheel1_s = pymunk.Circle(wheel1_b, radius)
    wheel1_s.friction = 1.5
    wheel1_s.color = wheel_color
    space.add(wheel1_b, wheel1_s)
    sprites.append((wheel1_b, wheel1_s))

    # second wheel
    mass = 10
    radius = 25
    moment = pymunk.moment_for_circle(mass, 20, radius)
    wheel2_b = pymunk.Body(mass, moment)
    wheel2_s = pymunk.Circle(wheel2_b, radius)
    wheel2_s.friction = 1.5
    wheel2_s.color = wheel_color
    space.add(wheel2_b, wheel2_s)
    sprites.append((wheel2_b, wheel2_s))

    # third wheel
    mass = 10
    radius = 25
    moment = pymunk.moment_for_circle(mass, 20, radius)
    wheel3_b = pymunk.Body(mass, moment)
    wheel3_s = pymunk.Circle(wheel3_b, radius)
    wheel3_s.friction = 1.5
    wheel3_s.color = wheel_color
    space.add(wheel3_b, wheel3_s)
    sprites.append((wheel3_b, wheel3_s))

    # chassis
    mass = 100
    size = (50, 30)
    moment = pymunk.moment_for_box(mass, size)
    chassis_b = pymunk.Body(mass, moment)
    chassis_s = pymunk.Poly.create_box(chassis_b, size)
    space.add(chassis_b, chassis_s)
    sprites.append((chassis_b, chassis_s))

    # plow
    mass = 50
    vertices = [(0, 0), (0, 50), (25, 0)]
    moment = pymunk.moment_for_poly(mass, vertices)
    plow_b = pymunk.Body(mass, moment)
    plow_s = pymunk.Poly(plow_b, vertices)
    space.add(plow_b, plow_s)
    sprites.append((plow_b, plow_s))

    wheel1_b.position = pos + (-55, 0)
    wheel2_b.position = pos + (55, 0)
    wheel3_b.position = pos + (0, 90)
    chassis_b.position = pos + (0, 30)
    plow_b.position = pos + (95, -20)

    space.add(pymunk.PinJoint(wheel1_b, chassis_b, (0, 0), (-25, -15)),
              pymunk.PinJoint(wheel1_b, chassis_b, (0, 0), (-25, 15)),
              pymunk.PinJoint(wheel2_b, chassis_b, (0, 0), (25, -15)),
              pymunk.PinJoint(wheel2_b, chassis_b, (0, 0), (25, 15)),
              pymunk.PinJoint(wheel3_b, chassis_b, (0, 0), (-25, 15)),
              pymunk.PinJoint(wheel3_b, chassis_b, (0, 0), (25, 15)),
              pymunk.PinJoint(chassis_b, plow_b, (25, 25), (0, 50)),
              pymunk.PinJoint(wheel2_b, plow_b, (0, 0), (0, 0)),
              pymunk.PinJoint(wheel2_b, plow_b, (0, 0), (0, 50)))

    speed = 0
    motors = [
        pymunk.SimpleMotor(wheel1_b, chassis_b, speed),
        pymunk.SimpleMotor(wheel2_b, chassis_b, speed),
        pymunk.SimpleMotor(wheel3_b, chassis_b, speed)
    ]
    space.add(*motors)
    return motors, chassis_b
Esempio n. 38
0
def create_pogo1(space, x, y):
    pos = Vec2d(x, y)

    # carriage
    mass = 100
    size = (50, 30)
    moment = pymunk.moment_for_box(mass, size)
    carriage_b = pymunk.Body(mass, moment)
    carriage_s = pymunk.Poly.create_box(carriage_b, size)
    carriage_s.color = 255, 0, 0
    space.add(carriage_b, carriage_s)
    sprites.append((carriage_b, carriage_s))

    # left leg
    mass = 20
    left_leg_b = pymunk.Body(mass)
    size = (10, 100)
    left_leg_s = pymunk.Poly.create_box(left_leg_b, size)
    left_leg_s.color = 255, 0, 0
    space.add(left_leg_b, left_leg_s)
    sprites.append((left_leg_b, left_leg_s))

    # right leg
    mass = 20
    right_leg_b = pymunk.Body(mass)
    size = (10, 100)
    right_leg_s = pymunk.Poly.create_box(right_leg_b, size)
    right_leg_s.color = 255, 0, 0
    space.add(right_leg_b, right_leg_s)
    sprites.append((right_leg_b, right_leg_s))

    # left wheel
    mass = 10
    radius = 10
    moment = pymunk.moment_for_circle(mass, 0, radius)
    wheel1_b = pymunk.Body(mass, moment)
    wheel1_s = pymunk.Circle(wheel1_b, radius)
    wheel1_s.friction = 1.0
    wheel1_s.color = 0, 0, 0
    space.add(wheel1_b, wheel1_s)
    sprites.append((wheel1_b, wheel1_s))

    # right wheel
    mass = 10
    radius = 10
    moment = pymunk.moment_for_circle(mass, 0, radius)
    wheel2_b = pymunk.Body(mass, moment)
    wheel2_s = pymunk.Circle(wheel2_b, radius)
    wheel2_s.friction = 1.0
    wheel2_s.color = 0, 0, 0
    space.add(wheel2_b, wheel2_s)
    sprites.append((wheel2_b, wheel2_s))

    # stick
    mass = 20
    size = (40, 150)
    stick_b = pymunk.Body(mass)
    stick_s = pymunk.Poly.create_box(stick_b, size)
    stick_s.color = 0, 0, 255
    space.add(stick_b, stick_s)
    sprites.append((stick_b, stick_s))

    carriage_b.position = pos + (0, 100)
    left_leg_b.position = pos + (-25, 50)
    right_leg_b.position = pos + (25, 50)
    wheel1_b.position = pos + (-25, -50)
    wheel2_b.position = pos + (25, -50)
    stick_b.position = pos + (0, -50)

    space.add([
        pymunk.PinJoint(carriage_b, left_leg_b, (0, 0), (0, 100)),
        pymunk.PinJoint(carriage_b, left_leg_b, (25, 0), (0, 100)),
        pymunk.PinJoint(carriage_b, right_leg_b, (0, 0), (0, 100)),
        pymunk.PinJoint(carriage_b, right_leg_b, (25, 0), (0, 100)),
        pymunk.PinJoint(left_leg_b, wheel1_b, (5, 0), (0, 0)),
        pymunk.PinJoint(right_leg_b, wheel2_b, (5, 0), (0, 0))
    ])

    return carriage_b
Esempio n. 39
0
 def get_moment(self, model):
     return pymunk.moment_for_box(model.mass, (model.width, model.height))
Esempio n. 40
0
# setup the space
space = pymunk.Space(threaded=True)
space.gravity = 0, -9.8

fil = pymunk.ShapeFilter(group=1)

# ground
ground = pymunk.Segment(space.static_body, (-4, -0.1), (4, -0.1), 0.1)
ground.friction = 0.1
ground.filter = fil
space.add(ground)

# cart
cart_mass = 0.5
cart_size = 0.3, 0.2
cart_moment = pymunk.moment_for_box(cart_mass, cart_size)
cart_body = pymunk.Body(mass=cart_mass, moment=cart_moment)
cart_body.position = 0.0, cart_size[1] / 2
cart_shape = pymunk.Poly.create_box(cart_body, cart_size)
cart_shape.friction = ground.friction
space.add(cart_body, cart_shape)

# pendulum
pend_length = 0.6  # to center of mass
pend_size = 0.1, pend_length * 2  # to get CoM at 0.6 m
pend_mass = 0.2
pend_moment = 0.001
pend_body = pymunk.Body(mass=pend_mass, moment=pend_moment)
pend_body.position = cart_body.position[
    0], cart_body.position[1] + cart_size[1] / 2 + pend_length
pend_shape = pymunk.Poly.create_box(pend_body, pend_size)
Esempio n. 41
0
    def __init__(self, FPS=60.0, KP=200, KI=50, KD=25):
        #-----------------------------------------------------------------------------------------------------------------------------------
        self.FPS = 60.0  # 60 quadros por segundo
        #-----------------------------------------------------------------------------------------------------------------------------------
        ambiente = pymunk.Space()
        ambiente.gravity = 0, -98.1  ##x,y
        #-------------------------------------------------------------------------------------------------------------------------------piso
        piso_ponto_A = 0, 0
        piso_ponto_B = 640, 0
        piso_shape = pymunk.Segment(None, (piso_ponto_A), (piso_ponto_B), 2)
        piso_momento = pymunk.moment_for_segment(1000, (piso_ponto_A),
                                                 (piso_ponto_B), 2)
        piso_fisica = pymunk.Body(1, piso_momento, pymunk.Body.KINEMATIC)
        piso_shape.body = piso_fisica
        piso_shape.friction = 0.62

        ambiente.add(piso_fisica, piso_shape)
        #-----------------------------------------------------------------------------------------------------------------------------chassi
        chassi_posicao = 100, 35
        chassi_tamanho = 80, 20
        chassi_massa = 30  #gramas
        chassi_shape = pymunk.Poly.create_box(None, size=chassi_tamanho)
        chassi_momento = pymunk.moment_for_box(chassi_massa, chassi_tamanho)
        chassi_fisica = pymunk.Body(chassi_massa, chassi_momento,
                                    pymunk.Body.DYNAMIC)
        chassi_shape.body = chassi_fisica
        chassi_fisica.position = chassi_posicao
        chassi_shape.friction = 0.4

        ambiente.add(chassi_shape, chassi_fisica)
        #-------------------------------------------------------------------------------------------------------------------------R_traseira
        R_traseira_posicao = (chassi_posicao[0] -
                              (chassi_tamanho[0] / 2)) - 20, (
                                  chassi_posicao[1] - 20)
        R_traseira_massa = 10
        R_traseira_raio_in = 10
        R_traseira_raio_out = 10
        R_traseira_momento = pymunk.moment_for_circle(R_traseira_massa,
                                                      R_traseira_raio_in,
                                                      R_traseira_raio_out)
        R_traseira_fisica = pymunk.Body(R_traseira_massa, R_traseira_momento,
                                        pymunk.Body.DYNAMIC)
        R_traseira_shape = pymunk.Circle(R_traseira_fisica,
                                         R_traseira_raio_out)
        R_traseira_fisica.position = R_traseira_posicao
        R_traseira_shape.friction = 0.6

        ambiente.add(R_traseira_shape, R_traseira_fisica)
        #------------------------------------------------------------------------------------------------------------------------R_dianteira
        R_dianteira_posicao = (chassi_posicao[0] +
                               (chassi_tamanho[0] / 2)) + 20, (
                                   chassi_posicao[1] - 20)
        R_dianteira_massa = 10
        R_dianteira_raio_in = 10
        R_dianteira_raio_out = 10
        R_dianteira_momento = pymunk.moment_for_circle(R_dianteira_massa,
                                                       R_dianteira_raio_in,
                                                       R_dianteira_raio_out)
        R_dianteira_fisica = pymunk.Body(R_dianteira_massa,
                                         R_dianteira_momento,
                                         pymunk.Body.DYNAMIC)
        R_dianteira_shape = pymunk.Circle(R_dianteira_fisica,
                                          R_dianteira_raio_out)
        R_dianteira_fisica.position = R_dianteira_posicao
        R_dianteira_shape.friction = 0.6

        ambiente.add(R_dianteira_fisica, R_dianteira_shape)
        #----------------------------------------------------------------------------------------------------------------------------Pendulo
        pendulo_posicao = chassi_posicao[0], chassi_posicao[1] + 70
        pendulo_massa = 10
        pendulo_raio_in = 5
        pendulo_raio_out = 5
        pendulo_momento = pymunk.moment_for_circle(pendulo_massa,
                                                   pendulo_raio_in,
                                                   pendulo_raio_out)
        pendulo_fisica = pymunk.Body(pendulo_massa, pendulo_momento,
                                     pymunk.Body.DYNAMIC)
        pendulo_shape = pymunk.Circle(pendulo_fisica, pendulo_raio_out)
        pendulo_fisica.position = pendulo_posicao
        pendulo_shape.friction = 0.6
        pendulo_shape.color = (255, 0, 0, 255)  ##RGBA Vermelho

        junta_pendulo = pymunk.PinJoint(pendulo_fisica, chassi_fisica, (0, 0),
                                        (0, 10))

        # filtro de colisão - permite contato apenas com o chão
        chassi_shape.filter = pymunk.ShapeFilter(group=1)
        pendulo_shape.filter = chassi_shape.filter
        R_traseira_shape.filter = chassi_shape.filter
        R_dianteira_shape.filter = chassi_shape.filter

        ambiente.add(pendulo_fisica, pendulo_shape, junta_pendulo)

        #-----------------------------------------------------------------------------------------------------------------------------juntas
        ambiente.add(
            pymunk.PinJoint(R_traseira_fisica, chassi_fisica, (0, 0),
                            (-40, 10)),
            pymunk.PinJoint(R_dianteira_fisica, chassi_fisica, (0, 0),
                            (40, 10)),
            pymunk.PinJoint(R_dianteira_fisica, chassi_fisica, (0, 0),
                            (40, -10)),
            pymunk.PinJoint(R_traseira_fisica, chassi_fisica, (0, 0),
                            (-40, -10)))
        #------------------------------------------------------------------------------------------------------------------------------Motor
        velocidade = 0
        M_traseiro = pymunk.SimpleMotor(R_traseira_fisica, chassi_fisica,
                                        velocidade)
        M_dianteiro = pymunk.SimpleMotor(R_dianteira_fisica, chassi_fisica,
                                         velocidade)
        ambiente.add(M_traseiro, M_dianteiro)

        self.ambiente = ambiente
        self.pendulo_fisica = pendulo_fisica
        self.chassi_fisica = chassi_fisica
        self.M_dianteiro = M_dianteiro
        self.M_traseiro = M_traseiro

        self.rodas_controle = PIDControl(1.0 / FPS, KP, KI, KD)  # PID
        self.r = math.pi / 2  # referência a ser seguida
Esempio n. 42
0
    def setup_physics_model(self):
        if self.dirty and self.token.position:  # if token is on board
            # mass
            if self.mass != "inf":
                mass = self.mass
            else:
                mass = pymunk.inf

            # Sets the body type:
            # dynamic: Influenced by physic (e.g. actors)
            # static: not influenced by physics (e.g. plattforms)
            # kinematic: e.g. moving plattforms
            if self.can_move and not self.stable:
                body_type = pymunk_engine.Body.DYNAMIC
            elif self.can_move and self.stable:
                if self.gravity:
                    body_type = pymunk_engine.Body.DYNAMIC
                else:
                    body_type = pymunk_engine.Body.KINEMATIC
            else:
                body_type = pymunk_engine.Body.STATIC
            # Sets the moment
            # if stable: pymunk.inf: Object won't be rotated by an impulse
            if self.stable:
                moment = pymunk.inf
            elif self.shape_type == "rect":
                moment = pymunk_engine.moment_for_box(
                    mass,
                    (
                        self.size[0] * self.token.width,
                        self.size[1] * self.token.height,
                    ),
                )
            elif self.shape_type == "circle":
                moment = pymunk_engine.moment_for_circle(
                    mass, 0, self.size[0] * self.token.width / 2, (0, 0))
            elif self.shape_type == "line":
                moment = pymunk_engine.moment_for_segment(
                    mass,
                    pymunk.pygame_util.from_pygame(self.token.start_position,
                                                   self.token.board.image),
                    pymunk.pygame_util.from_pygame(self.token.end_position,
                                                   self.token.board.image),
                    self.token.thickness,
                )
            else:
                moment = pymunk_engine.moment_for_box(
                    mass=mass,
                    size=(self.size[0] * self.token.width,
                          self.size[1] * self.token.height))
            # create body
            self.body = pymunk_engine.Body(mass=mass,
                                           moment=moment,
                                           body_type=body_type)
            if not self.gravity:
                self.body.velocity_func = lambda body, gravity, damping, dt: None

            # Sets the shape-type
            if self.shape_type.lower() == "rect":
                shape = pymunk.Poly.create_box(
                    self.body,
                    (self.size[0] * self.token.width,
                     self.size[1] * self.token.height),
                )
            elif self.shape_type.lower() == "circle":
                shape = pymunk.Circle(
                    self.body,
                    self.size[0] * self.token.width / 2,
                    (0, 0),
                )
            elif self.shape_type.lower() == "line":
                try:
                    start_x, start_y = self.token.start_position[
                        0], self.token.start_position[1]
                    end_x, end_y = self.token.end_position[
                        0], self.token.end_position[1]
                    shape = pymunk.Segment(
                        self.body,
                        pymunk.pygame_util.from_pygame((start_x, start_y),
                                                       self.token.board.image),
                        pymunk.pygame_util.from_pygame((end_x, end_y),
                                                       self.token.board.image),
                        self.token.thickness,
                    )
                except AttributeError:
                    raise AttributeError("ERROR: token.board is not set.")
            # Adds object to space
            self.shape = shape
            PhysicsProperty.space.add(self.body, self.shape)
            if self.token.costume:
                self.body.position = pymunk.pygame_util.from_pygame(
                    self.token.center, self.token.board.image)
            self.body.size = (self.token.width, self.token.height)
            #self.body.angle = math.radians(
            #        self.token.direction_at_unit_circle - self.token.costume.orientation )
            if self.shape_type.lower() != "line":
                PhysicsProperty.space.reindex_shapes_for_body(self.body)
            self.shape.friction = self.friction
            shape.elasticity = self.elasticity
            shape.token = self.token
            self.shape.collision_type = self.token.__class__.class_id
            self.dirty = 0
            self.model_setup_complete = True
Esempio n. 43
0
    def __init__(self, space, maps, wheel_radius = 30):
        momentum = 1
        body_size = (200, 40)
        moment = pymunk.moment_for_box(momentum, body_size)
        self.body = pymunk.Body(momentum, moment)
        self.shape = pymunk.Poly.create_box(self.body, body_size)
        self.shape.mass = 5
        self.body.position = (200, 200)
        self.shape.body = self.body
        self.shape.color = (0, 0, 0, 255)

        human_moment = pymunk.moment_for_box(momentum, (30, 50))
        self.human_body = pymunk.Body(momentum, human_moment)
        self.human_shape = pymunk.Poly.create_box(self.human_body, (30, 50))
        self.human_body.position = (self.body.position.x, self.body.position.y+70)
        self.human_shape.body = self.human_body
        self.human_shape.color = (255, 0, 0, 255)
        self.human_joint = pymunk.PivotJoint(self.human_body, self.body, (-15, -20), (-15, 20))
        self.human_joint2 = pymunk.PivotJoint(self.human_body, self.body, (15, -20), (15, 20))

        head_moment = pymunk.moment_for_circle(momentum, 1, 1)
        self.head_body = pymunk.Body(momentum, head_moment)
        self.head_body.position = (self.human_body.position.x, self.human_body.position.y+70)
        self.head_shape = pymunk.Circle(self.head_body, 30)
        self.head_joint = pymunk.PivotJoint(self.head_body, self.human_body, (-10, -30), (-10, 20))
        self.head_joint2 = pymunk.PivotJoint(self.head_body, self.human_body, (10, -30), (10, 20))
        self.head_shape.collision_type = 1

        momentum = 100
        wheel_moment = pymunk.moment_for_circle(momentum, 10, wheel_radius)
        self.wheel1_body = pymunk.Body(momentum, wheel_moment)
        self.wheel1_body.position = self.body.position + (-60, -20)
        self.wheel1_shape = pymunk.Circle(self.wheel1_body, wheel_radius)
        self.wheel2_body = pymunk.Body(momentum, wheel_moment)
        self.wheel2_body.position = self.body.position + (60, -20)
        self.wheel2_shape = pymunk.Circle(self.wheel2_body, wheel_radius)

        self.wheel1_joint = pymunk.PivotJoint(self.body, self.wheel1_body, (-60, -20), (0, 0))
        self.wheel1_motor = pymunk.SimpleMotor(self.wheel1_body, self.body, 0)
        self.wheel2_joint = pymunk.PivotJoint(self.body, self.wheel2_body, (60, -20), (0, 0))

        self.wheel1_shape.friction = 1
        self.wheel1_shape.color = (200, 200, 200)
        self.wheel2_shape.friction = 1
        self.wheel2_shape.color = (200, 200, 200)

        space.add(self.body, self.shape)
        space.add(self.human_body, self.human_shape, self.human_joint, self.human_joint2)
        space.add(self.head_body, self.head_shape, self.head_joint, self.head_joint2)
        space.add(self.wheel1_body, self.wheel1_shape, self.wheel1_joint, self.wheel1_motor)
        space.add(self.wheel2_body, self.wheel2_shape, self.wheel2_joint)

        shape_filter = pymunk.ShapeFilter(group=1)
        self.shape.filter = shape_filter
        self.human_shape.filter = shape_filter
        self.head_shape.filter = shape_filter
        self.wheel1_shape.filter = shape_filter
        self.wheel1_motor.filter = shape_filter
        self.wheel2_shape.filter = shape_filter

        self.is_dead = False
        self.tick = 0
        self.prev_dist = 9999
        self.speed = 0
        self.face = pygame.image.load("normal.png")
        self.face = pygame.transform.scale(self.face, (90, 90))

        self.check = 0
        self.prev_check = 0
        self.timer = 0
        self.total_reward = 0

        self.maps = maps

        self.c_handler = space.add_collision_handler(1, 2)
        self.c_handler.begin = self.collision_handler
Esempio n. 44
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.prog = self.ctx.program(
            vertex_shader='''
                #version 330

                uniform vec4 Camera;

                // Per vertex
                in vec2 in_vert;
                in vec2 in_texture;

                // Per instance
                in vec3 in_pos;
                in vec2 in_size;
                in vec4 in_tint;

                out vec2 v_vert;
                out vec2 v_texture;
                out vec4 v_tint;

                void main() {
                    mat2 rotate = mat2(
                        cos(in_pos.z), sin(in_pos.z),
                        -sin(in_pos.z), cos(in_pos.z)
                    );
                    v_vert = rotate * (in_vert * in_size) + in_pos.xy;
                    gl_Position = vec4((v_vert - Camera.xy) / Camera.zw, 0.0, 1.0);
                    v_texture = in_texture;
                    v_tint = in_tint;
                }
            ''',
            fragment_shader='''
                #version 330

                uniform sampler2D Texture;

                in vec2 v_vert;
                in vec2 v_texture;
                in vec4 v_tint;

                out vec4 f_color;

                void main() {
                    vec4 tex = texture(Texture, v_texture);
                    vec3 color = tex.rgb * (1.0 - v_tint.a) + v_tint.rgb * v_tint.a;
                    f_color = vec4(color, tex.a);
            }
            ''',
        )

        self.tex1 = self.load_texture_2d('crate.png')
        self.tex1.use(0)

        self.tex2 = self.load_texture_2d('ball.png')
        self.tex2.use(1)

        vertices = np.array([
            -1.0,
            -1.0,
            0.0,
            0.0,
            -1.0,
            1.0,
            0.0,
            1.0,
            1.0,
            -1.0,
            1.0,
            0.0,
            1.0,
            1.0,
            1.0,
            1.0,
        ])

        vbo1 = self.ctx.buffer(vertices.astype('f4'))

        self.vbo2 = self.ctx.buffer(reserve=1024 * 1024)

        vao_content = [
            (vbo1, '2f 2f', 'in_vert', 'in_texture'),
            (self.vbo2, '3f 2f 4f/i', 'in_pos', 'in_size', 'in_tint'),
        ]

        self.vao = self.ctx.vertex_array(self.prog, vao_content)

        self.space = pymunk.Space()
        self.space.gravity = (0.0, -900.0)

        shape = pymunk.Segment(self.space.static_body, (5, 100), (595, 100),
                               1.0)
        shape.friction = 1.0
        self.space.add(shape)

        self.bodies = []
        self.balls = []

        for x in range(5):
            for y in range(10):
                size = 20
                mass = 10.0
                moment = pymunk.moment_for_box(mass, (size, size))
                body = pymunk.Body(mass, moment)
                body.position = Vec2d(300 + x * 50, 105 + y * (size + 0.1))
                shape = pymunk.Poly.create_box(body, (size, size))
                shape.friction = 0.3
                self.space.add(body, shape)
                self.bodies.append(body)
Esempio n. 45
0
    def construct(self):
        space = pymunk.Space()
        space.gravity = 0, -9820

        ground = space.static_body
        grd_seg = pymunk.Segment(ground, (-10000, -2000), (10000, -2000), 0)
        grd_seg.friction = 0.8
        space.add(grd_seg)
        #space.add(ground, grd_box)

        mass = 10
        size = (1000, 1000)
        moment = pymunk.moment_for_box(mass, size)
        body = pymunk.Body(mass, moment)
        body.angle = 0.1
        body.position = 0, 3000

        box = pymunk.Poly.create_box(body, size)
        box.elasticity = 0
        box.friction = 0.5
        space.add(body, box)

        shape = Square()
        shape.stretch_to_fit_height(1)
        shape.stretch_to_fit_width(1)

        body2 = pymunk.Body(mass, moment)
        body2.angle = -0.1
        body2.position = 800, 4500

        box2 = pymunk.Poly.create_box(body2, size)
        box2.elasticity = 0
        box2.friction = 0.5
        space.add(body2, box2)

        shape = Square()
        shape.stretch_to_fit_height(1)
        shape.stretch_to_fit_width(1)
        shape.set_fill(DARK_BLUE, opacity=1)

        shape2 = Square()
        shape2.stretch_to_fit_height(1)
        shape2.stretch_to_fit_width(1)
        shape2.set_fill(DARK_BROWN, opacity=1)

        self.add(shape)
        self.add(shape2)
        self.add(
            Line(FRAME_X_RADIUS * LEFT,
                 FRAME_X_RADIUS * RIGHT).shift(2 * DOWN))

        run_time = 5
        last_t = 0
        shape_cons = []
        shape2_cons = []
        step = 1 / self.camera.frame_rate
        for t in range(int(run_time / step)):
            space.step(step)
            shape_cons.append((body.position / 1000, body.angle))
            shape2_cons.append((body2.position / 1000, body2.angle))

        self.play(PhysicsBody(shape, shape_cons),
                  PhysicsBody(shape2, shape2_cons),
                  run_time=run_time)