Esempio n. 1
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((600, 600))
    pygame.display.set_caption("Joints. Just wait and the L will tip over")
    clock = pygame.time.Clock()

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

    ############### Arm
    space_center = (300, 300)

    # upper_arm_body = pymunk.Body(body_type=pymunk.Body.STATIC)
    # upper_arm_body.position = space_center
    # upper_arm_body.angle = np.deg2rad(-45)
    # upper_arm_line = pymunk.Segment(upper_arm_body, (0, 0), (-200, 0), 5.0)
    # upper_arm_line.sensor = True # Disable collision
    # space.add(upper_arm_line)
 

    lower_arm_body = pymunk.Body(10, 10000, body_type=pymunk.Body.DYNAMIC)
    lower_arm_body.position = (300, 300)
    # lower_arm_body.angle = np.deg2rad(45)
    lower_arm_line = pymunk.Segment(lower_arm_body, (0, 0), (200, 0), 10.0)

    space.add(lower_arm_line)

    # rotation_center_body = pymunk.Body(body_type=pymunk.Body.STATIC)
    # rotation_center_body.position = (300, 300)
    # elbow_joint = pymunk.PinJoint(rotation_center_body, lower_arm_body, (0, 0), (0, 0))

    # space.add(elbow_joint)

    # stiffness = 100
    # damping = 100
    # # rotation_limit_spring = pymunk.DampedSpring(upper_arm_body, lower_arm_body, (-45, 45), (80, 0), 10.0, stiffness, damping)

    # space.add(upper_arm_line, lower_arm_body, lower_arm_box, elbow_joint)


    ############## L Shape
    # rotation_center_body = pymunk.Body(body_type = pymunk.Body.STATIC)
    # rotation_center_body.position = (300,300)

    # rotation_limit_body = pymunk.Body(body_type = pymunk.Body.STATIC) # 1
    # rotation_limit_body.position = (200,300)

    # body = pymunk.Body(10, 10000)
    # body.position = (300,300)
    # l1 = pymunk.Segment(body, (-150, 75), (150.0, -75.0), 5.0)
    # l2 = pymunk.Segment(body, (-150.0, 0), (-150.0, 50.0), 5.0)

    # rotation_center_joint = pymunk.PinJoint(body, rotation_center_body, (0,0), (0,0))
    # joint_limit = 25

    # stiffness = 5
    # damping = 100
    # rotation_limit_spring = pymunk.DampedSpring(body, rotation_limit_body, (-100,0), (0,0), 10.0, stiffness, damping)
    # rotation_limit_joint = pymunk.SlideJoint(body, rotation_limit_body, (-100,0), (0,0), 0, joint_limit) # 2

    # space.add(l1, l2, body, rotation_center_joint, rotation_limit_spring)


    #######################
    balls = []
    draw_options = pymunk.pygame_util.DrawOptions(screen)

    ticks_to_next_ball = 10
    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)

        ticks_to_next_ball -= 1
        if ticks_to_next_ball <= 0:
            ticks_to_next_ball = 25
            ball_shape = add_ball(space)
            balls.append(ball_shape)

        space.step(1/50.0)

        screen.fill((255,255,255))
        space.debug_draw(draw_options)

        pygame.display.flip()
        
        clock.tick(50)
Esempio n. 2
0
 def testSurfaceVelocity(self):
     b1 = p.Body(1, 1)
     c = p.Circle(b1, 1)
     self.assertEqual(c.surface_velocity, (0, 0))
     c.surface_velocity = (1, 2)
     self.assertEqual(c.surface_velocity, (1, 2))
Esempio n. 3
0
 def testFilter(self):
     b1 = p.Body(1, 1)
     c = p.Circle(b1, 1)
     self.assertEqual(c.filter, p.ShapeFilter(0, 0xffffffff, 0xffffffff))
     c.filter = p.ShapeFilter(1, 0xfffffff2, 0xfffffff3)
     self.assertEqual(c.filter, p.ShapeFilter(1, 0xfffffff2, 0xfffffff3))
Esempio n. 4
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. 5
0
 def testElasticity(self):
     b1 = p.Body(1, 1)
     c = p.Circle(b1, 1)
     self.assertEqual(c.elasticity, 0)
     c.elasticity = 1
     self.assertEqual(c.elasticity, 1)
Esempio n. 6
0
import pymunk  # Import pymunk..

space = pymunk.Space()  # Create a Space which contain the simulation
space.gravity = 0, -1000  # Set its gravity

body = pymunk.Body(1, 1666)  # Create a Body with mass and moment
body.position = 50, 100  # Set the position of the body

poly = pymunk.Poly.create_box(body)  # Create a box shape and attach to body
space.add(body, poly)  # Add both body and shape to the simulation

while True:  # Infinite loop simulation
    space.step(0.02)  # Step the simulation one step forward
Esempio n. 7
0
 def __init__(self):
     self.x, self.y = 300, 400
     self.body = pymunk.Body(body_type=pymunk.Body.STATIC)
     self.shape = pymunk.Segment(self.body, (self.x, 100), (self.y, 100), 5)
     self.shape.elasticity = 1
     space.add(self.body, self.shape)
def main():
    pygame.init()
    screen = pygame.display.set_mode((600, 600))
    clock = pygame.time.Clock()
    running = True

    ### Physics stuff
    space = pymunk.Space()

    pointer_body = pymunk.Body()

    ps = [(80, 0), (0, 20), (0, -20)]
    moment = pymunk.moment_for_poly(1, ps)
    gun_body = pymunk.Body(1, moment)
    gun_body.position = 300, 300
    gun_shape = pymunk.Poly(gun_body, ps)

    rest_angle = 0
    stiffness = 125000.
    damping = 6000.

    rotary_spring = pymunk.constraint.DampedRotarySpring(
        pointer_body, gun_body, rest_angle, stiffness, damping)

    space.add(gun_body, gun_shape, rotary_spring)

    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                running = False
            elif event.type == KEYDOWN and event.key == K_p:
                pygame.image.save(screen, "aiming.png")
            elif event.type == pygame.MOUSEMOTION:
                mouse_pos = pymunk.pygame_util.get_mouse_pos(screen)
                pointer_body.position = mouse_pos
                pointer_body.angle = (pointer_body.position -
                                      gun_body.position).angle

            # to easily find good values for the damped rortary spring
            # as with most simulations done with pymunk, the imporant thing
            # is that it looks good, not the exact parameters
            elif event.type == KEYDOWN and event.key == K_q:
                rotary_spring.stiffness *= .5
                print(rotary_spring.stiffness, rotary_spring.damping)
            elif event.type == KEYDOWN and event.key == K_w:
                rotary_spring.stiffness *= 2
                print(rotary_spring.stiffness, rotary_spring.damping)
            elif event.type == KEYDOWN and event.key == K_a:
                rotary_spring.damping *= .5
                print(rotary_spring.stiffness, rotary_spring.damping)
            elif event.type == KEYDOWN and event.key == K_s:
                rotary_spring.damping *= 2
                print(rotary_spring.stiffness, rotary_spring.damping)

        ### Clear screen
        screen.fill(THECOLORS["white"])

        ### Draw stuff
        pymunk.pygame_util.draw(screen, space)

        ### Update physics
        dt = 1.0 / 60.0
        for x in range(1):
            space.step(dt)

        ### Flip screen
        pygame.display.flip()
        clock.tick(50)
Esempio n. 9
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((600, 600))
    clock = pygame.time.Clock()

    space = pymunk.Space()
    space.gravity = 0, 980
    static = [
        pymunk.Segment(space.static_body, (0, -50), (-50, 650), 5),
        pymunk.Segment(space.static_body, (0, 650), (650, 650), 5),
        pymunk.Segment(space.static_body, (650, 650), (650, -50), 5),
        pymunk.Segment(space.static_body, (-50, -50), (650, -50), 5),
    ]
    for s in static:
        s.collision_type = 1
    space.add(static)

    def pre_solve(arb, space, data):
        s = arb.shapes[0]
        space.remove(s.body, s)
        return False

    space.add_collision_handler(0, 1).pre_solve = pre_solve

    terrain_surface = pygame.Surface((600, 600))
    terrain_surface.fill(pygame.color.THECOLORS["white"])

    color = pygame.color.THECOLORS["pink"]
    pygame.draw.circle(terrain_surface, color, (450, 120), 100)
    generate_geometry(terrain_surface, space)
    for x in range(25):
        mass = 1
        moment = pymunk.moment_for_circle(mass, 0, 10)
        body = pymunk.Body(mass, moment)
        body.position = 450, 120
        shape = pymunk.Circle(body, 10)
        shape.friction = .5
        space.add(body, shape)

    draw_options = pymunk.pygame_util.DrawOptions(screen)
    pymunk.pygame_util.positive_y_is_up = False

    fps = 60
    while True:
        for event in pygame.event.get():
            if event.type == QUIT or \
                event.type == KEYDOWN and (event.key in [K_ESCAPE, K_q]):
                sys.exit(0)
            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 3:
                pass
            elif event.type == KEYDOWN and event.key == K_r:
                terrain_surface.fill(pygame.color.THECOLORS["white"])
                for s in space.shapes:
                    if hasattr(s, "generated") and s.generated:
                        space.remove(s)

            elif event.type == KEYDOWN and event.key == K_g:
                generate_geometry(terrain_surface, space)

            elif event.type == KEYDOWN and event.key == K_p:
                pygame.image.save(screen, "deformable.png")

        if pygame.mouse.get_pressed()[0]:
            if pygame.key.get_mods() & KMOD_SHIFT:
                mass = 1
                moment = pymunk.moment_for_circle(mass, 0, 10)
                body = pymunk.Body(mass, moment)
                body.position = event.pos
                shape = pymunk.Circle(body, 10)
                shape.friction = .5
                space.add(body, shape)
            else:
                color = pygame.color.THECOLORS["pink"]
                pos = pygame.mouse.get_pos()
                pygame.draw.circle(terrain_surface, color, pos, 25)

        space.step(1. / fps)

        screen.fill(pygame.color.THECOLORS["white"])
        screen.blit(terrain_surface, (0, 0))
        space.debug_draw(draw_options)
        draw_helptext(screen)
        pygame.display.flip()

        clock.tick(fps)
        pygame.display.set_caption("fps: " + str(clock.get_fps()))
Esempio n. 10
0
while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
        elif event.type == KEYDOWN and event.key == K_ESCAPE:
            running = False
        elif event.type == KEYDOWN and event.key == K_p:
            pygame.image.save(screen, 'bouncing_balls.png')

    ticks_to_next_ball -= 1
    if ticks_to_next_ball <= 0:
        ticks_to_next_ball = 100
        mass = 10
        radius = 25
        inertia = pymunk.moment_for_circle(mass, 0, radius, (0, 0))
        body = pymunk.Body(mass, inertia)
        x = random.randint(115, 350)
        body.position = x, 400
        shape = pymunk.Circle(body, radius, (0, 0))
        shape.elasticity = 0.95
        shape.friction = 0.9
        space.add(body, shape)
        balls.append(shape)

    screen.fill(THECOLORS['white'])

    balls_to_remove = []
    for ball in balls:
        if ball.body.position.y < 100: balls_to_remove.append(ball)

    for ball in balls_to_remove:
 def build_wall(self, point_a, point_b, thickness=5):
     body = pm.Body(body_type=pm.Body.STATIC)
     shape = pm.Segment(body, point_a, point_b, thickness)
     shape.color = GRAY
     return body, shape
Esempio n. 12
0
def fill_space(space, custom_color=(255,255,0,255)):
    captions = []
    
    ### Static
    captions.append(((50,680), "Static Shapes"))

    #Static Segments
    segments = [ pymunk.Segment(space.static_body, (10, 400), (10, 600), 0)
                ,pymunk.Segment(space.static_body, (20, 400), (20, 600), 1)
                ,pymunk.Segment(space.static_body, (30, 400), (30, 600), 3)
                ,pymunk.Segment(space.static_body, (50, 400), (50, 600), 5)
                ]  
    space.add(segments)
    
    b = pymunk.Body(body_type=pymunk.Body.STATIC)
    b.position = (40,630)
    b.angle = 3.14/7
    s = pymunk.Segment(b, (-30,0), (30,0), 2)
    space.add(s)
    
    # Static Circles
    b = pymunk.Body(body_type=pymunk.Body.STATIC)
    b.position = (120,630)
    s = pymunk.Circle(b, 10)
    space.add(s)
    
    b = pymunk.Body(body_type=pymunk.Body.STATIC)
    b.position = (120,630)
    s = pymunk.Circle(b, 10, (-30,0))
    space.add(s)
    
    b = pymunk.Body(body_type=pymunk.Body.STATIC)
    b.position = (120,560)
    b.angle = 3.14/4
    s = pymunk.Circle(b, 40)
    space.add(s)
    
    # Static Polys
    b = pymunk.Body(body_type=pymunk.Body.STATIC)
    b.position = (120,460)
    b.angle = 3.14/4
    s = pymunk.Poly(b, [(0, -25),(30, 25),(-30, 25)])
    space.add(s)
    
    b = pymunk.Body(body_type=pymunk.Body.STATIC)
    b.position = (120,500)
    t = pymunk.Transform(ty=-100)
    s = pymunk.Poly(b, [(0, -25),(30, 25),(-30, 25)], t, radius=3)
    space.add(s)
    
    b = pymunk.Body(body_type=pymunk.Body.STATIC)
    b.position = (50,430)
    t = pymunk.Transform(ty=-100)
    s = pymunk.Poly(b, [(0.0, -30.0), (19.0, -23.0), (30.0, -5.0), (26.0, 15.0), (10.0, 28.0), (-10.0, 28.0), (-26.0, 15.0), (-30.0, -5.0), (-19.0, -23.0)], t)
    space.add(s)
    
    ### Kinematic
    captions.append(((220,680), "Kinematic Shapes"))

    # Kinematic Segments
    b = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    segments = [ pymunk.Segment(b, (180, 400), (180, 600), 0)
                ,pymunk.Segment(b, (190, 400), (190, 600), 1)
                ,pymunk.Segment(b, (200, 400), (200, 600), 3)
                ,pymunk.Segment(b, (220, 400), (220, 600), 5)
                ]  
    space.add(segments)
    
    b = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    b.position = (210,630)
    b.angle = 3.14/7
    s = pymunk.Segment(b, (-30,0), (30,0), 2)
    space.add(s)
    
    # Kinematic Circles
    b = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    b.position = (290,630)
    s = pymunk.Circle(b, 10)
    space.add(s)
    
    b = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    b.position = (290,630)
    s = pymunk.Circle(b, 10, (-30,0))
    space.add(s)
    
    b = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    b.position = (290,560)
    b.angle = 3.14/4
    s = pymunk.Circle(b, 40)
    space.add(s)
    
    # Kinematic Polys
    b = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    b.position = (290,460)
    b.angle = 3.14/4
    s = pymunk.Poly(b, [(0, -25),(30, 25),(-30, 25)])
    space.add(s)
    
    b = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    b.position = (290,500)
    t = pymunk.Transform(ty=-100)
    s = pymunk.Poly(b, [(0, -25),(30, 25),(-30, 25)], t, radius=3)
    space.add(s)
    
    b = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    b.position = (230,430)
    t = pymunk.Transform(ty=-100)
    s = pymunk.Poly(b, [(19.0, -50.0), (30.0, -5.0), (26.0, 15.0), (10.0, 38.0), (-10.0, 38.0), (-26.0, 15.0), (-30.0, -5.0), (-19.0, -50.0)], t)
    space.add(s)

    ### Dynamic
    captions.append(((390,680), "Dynamic Shapes"))

    #Dynamic Segments
    b = pymunk.Body(1,1)
    segments = [pymunk.Segment(b, (350, 400), (350, 600), 0),
                pymunk.Segment(b, (360, 400), (360, 600), 1),
                pymunk.Segment(b, (370, 400), (370, 600), 3),
                pymunk.Segment(b, (390, 400), (390, 600), 5),
                ]  
    space.add(segments)
    
    b = pymunk.Body(1,1)
    b.position = (380,630)
    b.angle = 3.14/7
    s = pymunk.Segment(b, (-30,0), (30,0), 2)
    space.add(s)
    
    # Dynamic Circles
    b = pymunk.Body(1,1)
    b.position = (460,630)
    s = pymunk.Circle(b, 10)
    space.add(s)
    
    b = pymunk.Body(1,1)
    b.position = (460,630)
    s = pymunk.Circle(b, 10, (-30,0))
    space.add(s)
    
    b = pymunk.Body(1,1)
    b.position = (460,560)
    b.angle = 3.14/4
    s = pymunk.Circle(b, 40)
    space.add(s)
    
    # Dynamic Polys
    
    b = pymunk.Body(1,1)
    b.position = (460,460)
    b.angle = 3.14/4
    s = pymunk.Poly(b, [(0, -25),(30, 25),(-30, 25)])
    space.add(s)
    
    b = pymunk.Body(1,1)
    b.position = (460,500)    
    s = pymunk.Poly(b, [(0, -25),(30, 25),(-30, 25)], pymunk.Transform(ty=-100), radius=3)
    space.add(s)
    
    b = pymunk.Body(1,1)
    b.position = (400,430)
    s = pymunk.Poly(b, [(0, -50), (50, 0), (30, 50),(-30, 50),(-50, 0)], pymunk.Transform(ty=-100))
    space.add(s)
    
    ###Constraints
    
    # PinJoints
    captions.append(((560,660), "Pin Joints"))
    a = pymunk.Body(1,1)
    a.position = (550, 600)
    sa = pymunk.Circle(a, 20)
    b = pymunk.Body(1,1)
    b.position = (650, 620)
    sb = pymunk.Circle(b, 20)
    j = pymunk.PinJoint(a, b)
    space.add(sa, sb, a, b, j)
    
    a = pymunk.Body(1,1)
    a.position = (550,550)
    sa = pymunk.Circle(a, 20)
    b = pymunk.Body(1,1)
    b.position = (650,570)
    sb = pymunk.Circle(b, 20)
    j = pymunk.PinJoint(a, b, anchor_a=(0,20), anchor_b=(0,-20))
    space.add(sa, sb, a, b, j)
    
    # SlideJoints
    captions.append(((560,490), "Slide Joint"))
    a = pymunk.Body(1,1)
    a.position = (550,430)
    sa = pymunk.Circle(a, 20)
    b = pymunk.Body(1,1)
    b.position = (650,450)
    sb = pymunk.Circle(b, 20)
    j = pymunk.SlideJoint(a, b, anchor_a=(0,20), anchor_b=(0,-20), min=10, max=30)
    space.add(sa, sb, a, b, j)
    
    # PivotJoints
    captions.append(((560,390), "Pivot Joint"))
    a = pymunk.Body(1,1)
    a.position = (550,330)
    sa = pymunk.Circle(a, 20)
    b = pymunk.Body(1,1)
    b.position = (650,350)
    sb = pymunk.Circle(b, 20)
    j = pymunk.PivotJoint(a, b, (600,320))
    space.add(sa, sb, a, b, j)
    

    # GrooveJoints
    captions.append(((760,660), "Groove Joint"))
    a = pymunk.Body(1,1)
    a.position = (750,600)
    sa = pymunk.Circle(a, 20)
    b = pymunk.Body(1,1)
    b.position = (850,620)
    sb = pymunk.Circle(b, 20)
    j = pymunk.GrooveJoint(a, b, (790,610), (790,620), (840,620))
    space.add(sa, sb, a, b, j)
    
    # DampedSpring
    captions.append(((760,550), "Damped Spring"))
    a = pymunk.Body(1,1)
    a.position = (750,480)
    sa = pymunk.Circle(a, 20)
    b = pymunk.Body(1,1)
    b.position = (850,500)
    sb = pymunk.Circle(b, 20)
    j = pymunk.DampedSpring(a, b, (0,0), (0,10), 100, 1,1)
    space.add(sa, sb, a, b, j)
    
    # DampedRotarySpring
    captions.append(((740,430), "Damped Rotary Spring"))
    a = pymunk.Body(1,1)
    a.position = (750,350)
    sa = pymunk.Circle(a, 20)
    b = pymunk.Body(1,1)
    b.position = (850,380)
    sb = pymunk.Circle(b, 20)
    j = pymunk.DampedRotarySpring(a, b, 10, 1, 1)
    space.add(sa, sb, a, b, j)

    # RotaryLimitJoint
    captions.append(((740,300), "Rotary Limit Joint"))
    a = pymunk.Body(1,1)
    a.position = (750,220)
    sa = pymunk.Circle(a, 20)
    b = pymunk.Body(1,1)
    b.position = (850,250)
    sb = pymunk.Circle(b, 20)
    j = pymunk.RotaryLimitJoint(a, b, 1, 2)
    b.angle = 3
    space.add(sa, sb, a, b, j)

    # RatchetJoint
    captions.append(((740,170), "Ratchet Joint"))
    a = pymunk.Body(1,1)
    a.position = (750,100)
    sa = pymunk.Circle(a, 20)
    b = pymunk.Body(1,1)
    b.position = (850,120)
    sb = pymunk.Circle(b, 20)
    j = pymunk.RatchetJoint(a, b, 1, 0.1)
    b.angle = 3
    space.add(sa, sb, a, b, j)

    # GearJoint and SimpleMotor omitted since they are similar to the already 
    # added joints

    # TODO: more stuff here :)
    
    ### Other
    
    # Objects in custom color
    captions.append(((150,150), "Custom Color (static & dynamic)"))
    b = pymunk.Body(body_type=pymunk.Body.STATIC)
    b.position = (200, 200)
    s = pymunk.Circle(b, 40)
    s.color = custom_color
    space.add(s)
    
    b = pymunk.Body(1, 1)
    b.position = (300, 200)
    s = pymunk.Circle(b, 40)
    s.color = custom_color
    space.add(s)
    
    # Collision
    captions.append(((450,150), "Collisions"))
    b = pymunk.Body(body_type=pymunk.Body.STATIC)
    b.position = (470, 200)
    s = pymunk.Circle(b, 40)
    space.add(s)
    
    b = pymunk.Body(1, 1)
    b.position = (500, 250)
    s = pymunk.Circle(b, 40)
    space.add(s)

    # Sleeping
    captions.append(((50,150), "Sleeping"))
    b = pymunk.Body(1,1)
    b.position = (75, 200)
    space.sleep_time_threshold = 0.01
    s = pymunk.Circle(b, 40)
    space.add(s, b)
    b.sleep()
    space.step(0.000001)

    return captions
Esempio n. 13
0
def main():
    # Init vars
    running = True
    progress = True
    clock = pygame.time.Clock()
    size = width, height = 1024, 768
    screen = pygame.display.set_mode(size)
    surface = pygame.Surface(screen.get_size())

    # Physics
    space = pymunk.Space()
    space.gravity = (0.0, -900.0)
    draw_options = pymunk.pygame_util.DrawOptions(surface)

    fp = [(5, -5), (-85, 0), (5, 5)]
    mass = 100
    moment = pymunk.moment_for_poly(mass, fp)

    # Balls
    balls = []

    drawSegments(space)

    # Right flipper
    r_flipper_body = pymunk.Body(mass, moment)
    r_flipper_body.position = 600, 82
    r_flipper_shape = pymunk.Poly(r_flipper_body, fp)
    space.add(r_flipper_body, r_flipper_shape)

    r_flipper_joint_body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    r_flipper_joint_body.position = r_flipper_body.position
    j = pymunk.PinJoint(r_flipper_body, r_flipper_joint_body, (0, 0), (0, 0))
    s = pymunk.DampedRotarySpring(r_flipper_body, r_flipper_joint_body, 0.15,
                                  20000000, 900000)
    space.add(j, s)

    # Left flipper
    l_flipper_body = pymunk.Body(mass, moment)
    l_flipper_body.position = 380, 82
    l_flipper_shape = pymunk.Poly(l_flipper_body, [(-x, y) for x, y in fp])
    space.add(l_flipper_body, l_flipper_shape)

    l_flipper_joint_body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    l_flipper_joint_body.position = l_flipper_body.position
    j = pymunk.PinJoint(l_flipper_body, l_flipper_joint_body, (0, 0), (0, 0))
    s = pymunk.DampedRotarySpring(l_flipper_body, l_flipper_joint_body, -0.15,
                                  20000000, 900000)
    space.add(j, s)

    r_flipper_shape.group = l_flipper_shape.group = 1
    r_flipper_shape.elasticity = l_flipper_shape.elasticity = 0.4

    ### Main Loop ###
    while running:
        ### Clear screen and draw stuff
        surface.fill((0, 0, 0))
        drawStuff(surface)

        # Define mouse position
        mouseX = pygame.mouse.get_pos()[1]
        mouseY = pygame.mouse.get_pos()[0]

        # Events loop
        for event in pygame.event.get():
            # Manage quit / closing window event
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                elif event.key == K_j:
                    r_flipper_body.apply_impulse_at_local_point(
                        Vec2d.unit() * 40000, (-100, 0))
                elif event.key == K_f:
                    l_flipper_body.apply_impulse_at_local_point(
                        Vec2d.unit() * -40000, (-100, 0))
                elif event.type == KEYDOWN and event.key == K_b:
                    mass = 1
                    radius = 8
                    inertia = pymunk.moment_for_circle(mass, 0, radius, (0, 0))
                    body = pymunk.Body(mass, inertia)
                    x = random.randint(350, 600)
                    body.position = x, 400
                    shape = pymunk.Circle(body, radius, (0, 0))
                    shape.elasticity = 0.95
                    space.add(body, shape)
                    balls.append(shape)

        # Display Rasta Rockets
        space.debug_draw(draw_options)

        r_flipper_body.position = 600, 82
        l_flipper_body.position = 380, 82
        r_flipper_body.velocity = l_flipper_body.velocity = 0, 0

        # Remove any balls outside
        to_remove = []
        for ball in balls:
            if ball.body.position.get_distance((300, 300)) > 1000:
                to_remove.append(ball)

        for ball in to_remove:
            space.remove(ball.body, ball)
            balls.remove(ball)

        # Update physics
        dt = 1.0 / 60.0 / 5.
        for x in range(5):
            space.step(dt)

        clock.tick(50)
        screen.blit(surface, (0, 0))
        pygame.display.flip()
        pygame.display.set_caption(
            "Night Mission - PinBall - " + "FPS: " + str(clock.get_fps()) +
            " - Mouse Position : " +
            "mouseX: {0} - mouseY: {1}".format(mouseX, mouseY))
Esempio n. 14
0
def main():
    pygame.init()
    screen = pygame.display.set_mode(display_size, display_flags)
    width, height = screen.get_size()

    def to_pygame(p):
        """Small hack to convert pymunk to pygame coordinates"""
        return int(p.x), int(-p.y + height)

    def from_pygame(p):
        return to_pygame(p)

    clock = pygame.time.Clock()
    running = True
    font = pygame.font.Font(None, 16)

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

    ### Physics stuff
    space = pm.Space()
    space.gravity = (0.0, -1900.0)
    space.damping = 0.999  # to prevent it from blowing up.
    mouse_body = pm.Body(body_type=pm.Body.KINEMATIC)
    # static_body = pymunk.Space().static_body
    static_body = pm.Body(body_type=pm.Body.STATIC)
    static_body.position = (300, 300)
    static_lines = [
        pymunk.Segment(static_body, (50, -250), (250, -50), 2.0)
        # pymunk.Segment(static_body, (408, 100), (600, 343.0), 2.0),
        # pymunk.Segment(static_body, (450, 75), (200, 343.0), 2.0),
        # pymunk.Segment(static_body, (470, 50), (300, 343.0), 2.0)
    ]
    for line in static_lines:
        line.elasticity = 0.6
        line.friction = 0.9
    space.add(static_lines)
    bodies = []
    for x in range(-100, 150, 50):
        x += width / 2
        offset_y = height / 2
        mass = 10
        radius = 25
        moment = pm.moment_for_circle(mass, 0, radius, (0, 0))
        body = pm.Body(mass, moment)
        body.position = (x, -125 + offset_y)
        body.start_position = Vec2d(body.position)
        shape = pm.Circle(body, radius)
        shape.elasticity = .99999
        space.add(body, shape)
        bodies.append(body)
        pj = pm.PinJoint(space.static_body, body, (x, 125 + offset_y), (0, 0))
        space.add(pj)
        reset_bodies(space)
    selected = None
    balls = []
    ticks_to_next_ball = 10
    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
        ticks_to_next_ball -= 1
        if ticks_to_next_ball <= 0:
            ticks_to_next_ball = 250
            ball_shape = add_ball(space)
            balls.append(ball_shape)
        ### Clear screen
        screen.fill(THECOLORS["black"])

        ### Draw stuff
        for c in space.constraints:
            pv1 = c.a.position + c.anchor_a
            pv2 = c.b.position + c.anchor_b
            p1 = to_pygame(pv1)
            p2 = to_pygame(pv2)
            pygame.draw.aalines(screen, THECOLORS["lightgray"], False,
                                [p1, p2])

        for ball in space.shapes:
            p = to_pygame(ball.body.position)
            drawcircle(screen, THECOLORS["lightgray"], p, int(ball.radius), 0)

        # pygame.draw.lines(screen, THECOLORS["red"], False, [p1, p2])

        ### Update physics
        fps = 50
        iterations = 25
        dt = 1.0 / float(fps) / float(iterations)
        for x in range(
                iterations):  # 10 iterations to get a more stable simulation
            space.step(dt)

        draw_options = pm.pygame_util.DrawOptions(screen)
        space.debug_draw(draw_options)

        pygame.display.flip()
        clock.tick(fps)
Esempio n. 15
0
import pymunk
import pyglet
import random

space_list = []
wall_list = []

body = pymunk.Body(1, 100)
player = pymunk.Poly.create_box(body, size=(25, 20))
body.position = 120, 180

upper_player = pymunk.Segment(body, (0, 20), (0, 30), radius=10)
upper_player.position = 120, 210

damp_level = 1


def zero_gravity(body, gravity, damping, dt):
    pymunk.Body.update_velocity(body, (0, -1000), damp_level, dt)


body.velocity_func = zero_gravity

lower_body = pymunk.Body(1, 100, pymunk.Body.KINEMATIC)
lower_body.position = 240, random.randint(-10, 20)
lower_pipe = pymunk.Poly.create_box(lower_body, size=(30, 200))

upper_body = pymunk.Body(1, 100, pymunk.Body.KINEMATIC)
upper_body.position = 240, random.randint(340, 370)
upper_pipe = pymunk.Poly.create_box(upper_body, size=(30, 200))
Esempio n. 16
0
def run():
    pygame.init()
    pygame.display.set_caption("Launch and Smash")
    screen = pygame.display.set_mode((width, height))
    clock = pygame.time.Clock()
    font = pygame.font.SysFont("Arial", 16)

    # We will draw two versions of the Pymunk Space, each on a separate surface
    # to make it easy to show both at the same time.
    surf1 = pygame.Surface((300, 300))

    # Setup the base Pymunk Space.
    space1 = pymunk.Space()
    space1.gravity = 0, -1000
    space1.sleep_time_threshold = 0.1

    draw_options1 = pymunk.pygame_util.DrawOptions(surf1)

    box = [(5, 5), (295, 5), (295, 295), (5, 295)]
    for i, p1 in enumerate(box):
        if i + 1 >= len(box):
            p2 = box[0]
        else:
            p2 = box[i + 1]
        l = pymunk.Segment(space1.static_body, p1, p2, 5)
        l.elasticity = 0.5
        l.friction = 1

        space1.add(l)

    template_box = pymunk.Poly.create_box(pymunk.Body(), (20, 20))
    template_box.mass = 1
    template_box.friction = 1

    for x in range(3):
        for y in range(7):
            box = template_box.copy()
            box.body.position = 200 + x * 30, 10 + y * 20
            space1.add(box, box.body)

    b = pymunk.Body()
    b.position = 30, 100
    ball = pymunk.Circle(b, 20)
    ball.mass = 20
    ball.friction = 1
    ball.color = THECOLORS['red']
    space1.add(ball, b)

    # this is the same as space2 = copy.deepcopy(space1)
    space2 = space1.copy()
    space2.sleep_time_threshold = float('inf')

    backup1 = space1.copy()
    backup2 = space2.copy()

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
            elif event.type == KEYDOWN and (event.key in [K_ESCAPE, K_q]):
                pygame.quit()
            elif event.type == KEYDOWN and event.key == K_s:
                with open("copy_and_pickle.pickle", "wb") as f:
                    pickle.dump([space1, space2], f)
            elif event.type == KEYDOWN and event.key == K_l:
                with open("copy_and_pickle.pickle", "rb") as f:
                    (space1, space2) = pickle.load(f)

            elif event.type == KEYDOWN and event.key == K_r:
                space1 = backup1
                space2 = backup2
                backup1 = space1.copy()
                backup2 = space2.copy()
            elif event.type == KEYDOWN and event.key == K_SPACE:
                # find all bodies with a circle shape in all spaces
                for s in space1.shapes + space2.shapes:
                    if isinstance(s, pymunk.Circle) and s.body != None:
                        s.body.apply_impulse_at_local_point((20000, 0))
            elif event.type == KEYDOWN and event.key == K_p:
                pygame.image.save(screen, "copy_and_pickle.png")

        ### Clear screen
        screen.fill(THECOLORS["white"])

        ### Draw stuff
        surf1.fill(THECOLORS["black"])

        space1.debug_draw(draw_options1)

        screen.blit(surf1, (50, 100))

        ### Update physics
        fps = 60
        dt = 1. / fps
        space1.step(dt)
        space2.step(dt)

        ### Info and flip screen
        def dt(txt, pos):
            screen.blit(font.render(txt, 1, THECOLORS["black"]), pos)
            # dt("space.sleep_time_threshold set to 0.5 seconds", (50,80))

        dt("fps: " + str(clock.get_fps()), (0, 0))
        dt("Press SPACE to give an impulse to the ball.", (5, height - 50))
        dt("Press S to save the current state to file, press L to load it.",
           (5, height - 35))
        dt("Press R to reset, ESC or Q to quit", (5, height - 20))

        pygame.display.flip()
        clock.tick(fps)
Esempio n. 17
0
def run():
    config = pyglet.gl.Config(sample_buffers=1, samples=2, double_buffer=True)
    window = pyglet.window.Window(config=config, vsync=False)
    space = pymunk.Space()

    space.gravity = 0, -900
    space.damping = .999
    c = Vec2d(window.width / 2., window.height / 2.)

    ### WEB
    web_group = 1
    bs = []
    dist = .3

    cb = pymunk.Body(1, 1)
    cb.position = c
    s = pymunk.Circle(cb, 15)  # to have something to grab
    s.filter = pymunk.ShapeFilter(group=web_group)
    s.ignore_draw = True
    space.add(cb, s)

    # generate each crossing in the net
    for x in range(0, 101):
        b = pymunk.Body(1, 1)
        v = Vec2d.unit()
        v.angle_degrees = x * 18
        scale = window.height / 2. / 6. * .5

        dist += 1 / 18.
        dist = dist ** 1.005

        offset = 0
        offset = [0.0, -0.80, -1.0, -0.80][((x * 18) % 360) // 18 % 4]
        offset = .8 + offset

        offset *= dist ** 2.8 / 100.

        # print "offset", offset

        v.length = scale * (dist + offset)

        b.position = c + v
        s = pymunk.Circle(b, 15)
        s.filter = pymunk.ShapeFilter(group=web_group)
        s.ignore_draw = True
        space.add(b, s)
        bs.append(b)

    def add_joint(a, b):
        rl = a.position.get_distance(b.position) * 0.9
        stiffness = 5000.
        damping = 100
        j = pymunk.DampedSpring(a, b, (0, 0), (0, 0), rl, stiffness, damping)
        j.max_bias = 1000
        # j.max_force = 50000
        space.add(j)

    for b in bs[:20]:
        add_joint(cb, b)

    for i in range(len(bs) - 1):
        add_joint(bs[i], bs[i + 1])

        i2 = i + 20
        if len(bs) > i2:
            add_joint(bs[i], bs[i2])

    ### WEB ATTACH POINTS
    static_bs = []
    for b in bs[-17::4]:
        static_body = pymunk.Body(body_type=pymunk.Body.STATIC)
        static_body.position = b.position
        static_bs.append(static_body)

        j = pymunk.PivotJoint(static_body, b, static_body.position)
        j = pymunk.DampedSpring(static_body, b, (0, 0), (0, 0), 0, 0, 0)
        j.damping = 100
        j.stiffness = 20000
        space.add(j)

    ### ALL SETUP DONE

    def update(dt):
        # Note that we dont use dt as input into step. That is because the
        # simulation will behave much better if the step size doesnt change
        # between frames.
        r = 10
        for x in range(r):
            space.step(1. / 30. / r)

    pyglet.clock.schedule_interval(update, 1 / 30.)

    selected = None
    selected_joint = None
    mouse_body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)

    @window.event
    def on_mouse_press(x, y, button, modifiers):
        mouse_body.position = x, y
        hit = space.point_query_nearest((x, y), 10, pymunk.ShapeFilter())
        if hit != None:
            global selected
            body = hit.shape.body
            rest_length = mouse_body.position.get_distance(body.position)
            stiffness = 1000
            damping = 10
            selected = pymunk.DampedSpring(mouse_body, body, (0, 0), (0, 0), rest_length, stiffness, damping)
            space.add(selected)

    @window.event
    def on_mouse_release(x, y, button, modifiers):
        global selected
        if selected != None:
            space.remove(selected)
            selected = None

    @window.event
    def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
        mouse_body.position = x, y

    @window.event
    def on_key_press(symbol, modifiers):
        if symbol == pyglet.window.key.P:
            pyglet.image.get_buffer_manager().get_color_buffer().save('spiderweb.png')

    fps_display = pyglet.clock.ClockDisplay()

    @window.event
    def on_draw():
        pyglet.gl.glClearColor(240, 240, 240, 255)
        window.clear()

        fps_display.draw()

        # static attach points
        pyglet.gl.glColor3f(1, 0, 1)
        pyglet.gl.glPointSize(6)
        a = []
        for b in static_bs:
            a += [b.position.x, b.position.y]
            pyglet.graphics.draw(len(a) // 2, pyglet.gl.GL_POINTS, ('v2f', a))

        # web crossings / bodies
        pyglet.gl.glColor3f(.8, .8, .8)
        a = []
        for b in bs:
            a += [b.position.x, b.position.y]
        pyglet.gl.glPointSize(4)
        pyglet.graphics.draw(len(a) // 2, pyglet.gl.GL_POINTS, ('v2f', a))

        # web net / constraints
        a = []
        for j in space.constraints:
            a += [j.a.position.x, j.a.position.y, j.b.position.x, j.b.position.y]
            pass

        pyglet.graphics.draw(len(a) // 2, pyglet.gl.GL_LINES, ('v2f', a))

        # anything else

    pyglet.app.run()
Esempio n. 18
0
def add_pump(space):
    body = pymunk.Body()
    body.position = (70, 585)
    shape = pymunk.Poly.create_box(body, (15, 20), (0, 0), 0)
    space.add(shape)
    return shape
Esempio n. 19
0
 def add(self, x, y, koef):
     self.body = pymunk.Body(body_type=pymunk.Body.STATIC)
     self.shape = pymunk.Segment(self.body, (x[0], 800 - x[1]),
                                 (y[0], 800 - y[1]), 1)
     self.shape.elasticity = koef
     space.add(self.body, self.shape)
Esempio n. 20
0
def main():

    pygame.init()
    screen = pygame.display.set_mode(display_size, display_flags)
    width, height = screen.get_size()

    def to_pygame(p):
        """Small hack to convert pymunk to pygame coordinates"""
        return int(p.x), int(-p.y + height)

    def from_pygame(p):
        return to_pygame(p)

    clock = pygame.time.Clock()
    running = True
    font = pygame.font.Font(None, 16)

    ### Physics stuff
    space = pm.Space(iterations=1)
    space.gravity = (0.0, -1900.0)
    space.damping = 0.999  # to prevent it from blowing up.
    static_body = pm.Body()
    mouse_body = pm.Body()

    bodies = []
    for x in range(-100, 150, 50):
        x += width / 2
        offset_y = height / 2
        mass = 10
        radius = 25
        moment = pm.moment_for_circle(mass, 0, radius, (0, 0))
        body = pm.Body(mass, moment)
        body.position = (x, -125 + offset_y)
        body.start_position = Vec2d(body.position)
        shape = pm.Circle(body, radius)
        shape.elasticity = 0.9999999
        space.add(body, shape)
        bodies.append(body)
        pj = pm.PinJoint(static_body, body, (x, 125 + offset_y), (0, 0))
        space.add(pj)

    reset_bodies(space)
    selected = None

    if not is_interactive:
        pygame.time.set_timer(USEREVENT + 1, 70000)  # apply force
        pygame.time.set_timer(USEREVENT + 2, 120000)  # reset
        pygame.event.post(pygame.event.Event(USEREVENT + 1))
        pygame.mouse.set_visible(False)

    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            elif event.type == KEYDOWN and event.key == K_p:
                pygame.image.save(screen, "newtons_cradle.png")

            if event.type == pygame.USEREVENT + 1:
                r = random.randint(1, 4)
                for body in bodies[0:r]:
                    body.apply_impulse((-6000, 0))
            if event.type == pygame.USEREVENT + 2:
                reset_bodies(space)

            elif event.type == KEYDOWN and event.key == K_r and is_interactive:
                reset_bodies(space)
            elif event.type == KEYDOWN and event.key == K_f and is_interactive:
                r = random.randint(1, 4)
                for body in bodies[0:r]:
                    body.apply_impulse((-6000, 0))

            elif event.type == MOUSEBUTTONDOWN and is_interactive:
                if selected != None:
                    space.remove(selected)
                p = from_pygame(Vec2d(event.pos))
                shape = space.point_query_first(p)
                if shape != None:
                    rest_length = mouse_body.position.get_distance(
                        shape.body.position)
                    ds = pm.DampedSpring(mouse_body, shape.body, (0, 0),
                                         (0, 0), rest_length, 1000, 10)
                    space.add(ds)
                    selected = ds

            elif event.type == MOUSEBUTTONUP and is_interactive:
                if selected != None:
                    space.remove(selected)
                    selected = None

            elif event.type == KEYDOWN:
                running = False
            elif event.type == MOUSEBUTTONDOWN:
                running = False

        mpos = pygame.mouse.get_pos()
        p = from_pygame(Vec2d(mpos))
        mouse_body.position = p

        ### Clear screen
        screen.fill(THECOLORS["black"])

        ### Draw stuff
        for c in space.constraints:
            pv1 = c.a.position + c.anchr1
            pv2 = c.b.position + c.anchr2
            p1 = to_pygame(pv1)
            p2 = to_pygame(pv2)
            pygame.draw.aalines(screen, THECOLORS["lightgray"], False,
                                [p1, p2])

        for ball in space.shapes:
            p = to_pygame(ball.body.position)
            drawcircle(screen, ball.color, p, int(ball.radius), 0)
            #pygame.draw.circle(screen, ball.color, p, int(ball.radius), 0)

        ### Update physics
        fps = 50
        iterations = 25
        dt = 1.0 / float(fps) / float(iterations)
        for x in range(
                iterations):  # 10 iterations to get a more stable simulation
            space.step(dt)

        ### Flip screen
        if is_interactive:
            screen.blit(
                font.render("fps: " + str(clock.get_fps()), 1,
                            THECOLORS["white"]), (0, 0))
            screen.blit(
                font.render("Press left mouse button and drag to interact", 1,
                            THECOLORS["darkgrey"]), (5, height - 35))
            screen.blit(
                font.render("Press R to reset, any other key to quit", 1,
                            THECOLORS["darkgrey"]), (5, height - 20))

        pygame.display.flip()
        clock.tick(fps)
Esempio n. 21
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.i_body = pymunk.Body()
        self.shape = pymunk.Circle(self.body, self.RADIUS)
        self.shape.density = 1
Esempio n. 22
0
 def __init__(self, name):
     self.body = pk.Body()
     self.name = name
     self.shape = self.set_dimensions()
Esempio n. 23
0
 def testSensor(self):
     b1 = p.Body(1, 1)
     c = p.Circle(b1, 1)
     self.assertFalse(c.sensor)
     c.sensor = True
     self.assertTrue(c.sensor)
 def add_wall(self, pt_from, pt_to):
     body = pymunk.Body(body_type=pymunk.Body.STATIC)
     ground_shape = pymunk.Segment(body, pt_from, pt_to, 0.0)
     ground_shape.friction = 0.8
     ground_shape.elasticity = .99
     self.space.add(ground_shape)
Esempio n. 25
0
 def testFriction(self):
     b1 = p.Body(1, 1)
     c = p.Circle(b1, 1)
     self.assertEqual(c.friction, 0)
     c.friction = 1
     self.assertEqual(c.friction, 1)
Esempio n. 26
0

# Describe this function...
def from_pygame(_p):
    global space, _position, body, _x, bodies, _y, surface, shape, clock, color, mouse_body, moment, newX, event, position, point, p, hit, selected, c, rest_length, pv1, ball, ds, pv2, fps, p1, iterations, p2, dt, pj
    return to_pygame(_p)


import random
bodies = []
surface = pygame.display.set_mode((600, 600), pygame.RESIZABLE)
clock = pygame.time.Clock()
space = pymunk.Space()
space.gravity = ((0, (-1900)))
space.damping = 0.999
mouse_body = pymunk.Body(body_type=(pymunk.Body.KINEMATIC))
for _x in range(-100, 151, 50):
    moment = pymunk.moment_for_circle(10, 0, 25, (0, 0))
    body = pymunk.Body(10, moment)
    newX = _x + 300
    position = (newX, (-125 + 300))
    body.position = position
    body.start_position = (pymunk.Vec2d((body.position)))
    shape = pymunk.Circle(body, 25)
    shape.elasticity = 0.9999999
    space.add(body)
    space.add(shape)
    bodies.append(body)
    pj = pymunk.PinJoint((space.static_body), body, ((newX, (125 + 300))),
                         ((0, 0)))
    space.add(pj)
Esempio n. 27
0
 def testCollisionType(self):
     b1 = p.Body(1, 1)
     c = p.Circle(b1, 1)
     self.assertEqual(c.collision_type, 0)
     c.collision_type = 1
     self.assertEqual(c.collision_type, 1)
Esempio n. 28
0
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)
pend_shape.filter = fil
Esempio n. 29
0
    def testInit(self):
        c = p.Poly(None, [(0, 0), (10, 10), (20, 0), (-10, 10)], None, 0)

        b = p.Body(1, 2)
        c = p.Poly(b, [(0, 0), (10, 10), (20, 0), (-10, 10)],
                   p.Transform.identity(), 6)
Esempio n. 30
0
 def _add_physics(self, space, ptA, ptB) -> pymunk.Segment:
     """Generates the physics body and shape need for pymunk"""
     body = pymunk.Body(0, 0, body_type=pymunk.Body.STATIC)
     seg = pymunk.Segment(body, ptA, ptB, self.width)
     space.add(body, seg)
     return seg