コード例 #1
0
ファイル: pyglet_util.py プロジェクト: llfkj/cymunk
def _draw_segment(segment, batch = None):
    body = segment.body
    pv1 = body.position + segment.a.rotated(body.angle)
    pv2 = body.position + segment.b.rotated(body.angle)
    
    d = pv2 - pv1
    a = -math.atan2(d.x, d.y)
    dx = segment.radius * math.cos(a)
    dy = segment.radius * math.sin(a)
    
    p1 = pv1 + Vec2d(dx,dy)
    p2 = pv1 - Vec2d(dx,dy)
    p3 = pv2 + Vec2d(dx,dy)
    p4 = pv2 - Vec2d(dx,dy)
           
    vs = [i for xy in [p1,p2,p3]+[p2,p3,p4] for i in xy]
    
    if hasattr(segment, "color"):
        color = segment.color  
    elif segment.body.is_static:
        color = (200, 200, 200)
    else:
        color = (0, 0, 255)
        
    l = len(vs)//2
    if batch == None:
        pyglet.graphics.draw(l, pyglet.gl.GL_TRIANGLES,
                            ('v2f', vs),
                            ('c3B', color * l))
    else:
        batch.add(l,pyglet.gl.GL_TRIANGLES, None,
                 ('v2f', vs),
                 ('c3B', color * l))
コード例 #2
0
    def apply_wheel_speed(self, wheel_speeds):
        """wheel_speeds in range 0 - 1

        lf, rf, lb, rb
        """
        # rotate ccw
        # wheel_speeds = [+1, +1, +1,+ 1] # go straight
        # wheel_speeds = [+1, +0, +0, +1] # go front left
        # wheel_speeds = [+0, -1, -1, 0] # go back left
        # wheel_speeds = [+1, -1, -1, +1] # strafe left
        # wheel_speeds = [+1, -1, +1, -1] # rotate CW

        imp_value = 1000  # strength of actuators
        # imp_value = 500

        # print(self.wheels)
        b = self.r.body
        ori = b.angle
        for v, wheel_speed in zip(self.wheels, wheel_speeds):
            wheel_pos, wheel_force_dir = v
            imp_vec = wheel_force_dir * imp_value * wheel_speed

            loc_wheel_pos = Vec2d(wheel_pos)
            loc_imp_vec = Vec2d(imp_vec)
            [v.rotate(ori) for v in [loc_wheel_pos, loc_imp_vec]]
            # print('wheel_pos')
            # print(loc_wheel_pos, wheel_pos)
            b.apply_impulse(loc_imp_vec, loc_wheel_pos)
コード例 #3
0
ファイル: main.py プロジェクト: homdx/kivy-cymunk-demo
 def wall_segments(self):
     w, h = self.size
     R = 200
     return [(Vec2d(-2 * R, -R), Vec2d(w + 2 * R, -R)),
             (Vec2d(-R, -2 * R), Vec2d(-R, h + 2 * R)),
             (Vec2d(-2 * R, h + R), Vec2d(w + 2 * R, h + R)),
             (Vec2d(w + R, h + 2 * R), Vec2d(w + R, -2 * R))], R
コード例 #4
0
    def init_physics():
        """ instead of using space as global variable """
        cls = PhysicsObject
        cls.space = Space()
        cls.space.gravity = defs.gravity

        ra = 100
        w, h = defs.map_size

        for x1, y1, x2, y2, ct in [
                (-100, defs.floor_level - ra, w + 100, defs.floor_level - ra, defs.BOTTOM_BOUND),
                (-ra, h + 100, -ra, -100, defs.LEFT_BOUND),
                (w + ra, h + 100, w + ra, -100, defs.RIGHT_BOUND)
              ]:
            wall = Segment(cls.space.static_body, Vec2d(x1, y1), Vec2d(x2, y2), ra)
            wall.elasticity = 0.6
            wall.friction = defs.friction
            wall.collision_type = ct
            cls.space.add_static(wall)
コード例 #5
0
    def carry_element(self, element, __dt=None):
        # unbind joint from element
        element.unjoint()

        # move it to center of cannon
        pivot = self.body.position + Vec2d(self.offset)
        element.body.position = pivot
        element.joint(self, pivot)

        self.bullets.append(element)
コード例 #6
0
 def shoot(self):
     if not self.bullets:
         return False
     impulse = Vec2d(0, defs.shoot_force)
     impulse.rotate(radians(self.aim))
     for x in self.bullets:
         x.unjoint()
         x.body.apply_impulse(impulse)
         x.shape.layers = defs.SHOOTED_THINGS_LAYER
         x.activate()
     self.bullets = []
     return True
コード例 #7
0
def post_solve_arrow_hit(space, arbiter):
    ti = Vec2d(arbiter.total_impulse['x'], arbiter.total_impulse['y'])
    if ti.length > 300:
        a, b = arbiter.shapes
        position = arbiter.contacts[0].position
        b.collision_type = 0
        b.group = 1
        other_body = a.body
        arrow_body = b.body
        #space.add_post_step_callback(stick_arrow_to_target, arrow_body, other_body, position, space)
        callbacks.append(
            [stick_arrow_to_target, arrow_body, other_body, position, space])
コード例 #8
0
def on_mouse_press(x, y, button, modifiers):
    mouse_body.position = x, y
    hit = space.nearest_point_query_nearest(Vec2d(x, y), 10)
    if hit != None:
        global selected
        body = hit.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)
コード例 #9
0
    def __init__(self):
        self.running = True
        self.drawing = True
        self.w, self.h = 600, 600
        self.screen = pygame.display.set_mode((self.w, self.h))
        self.clock = pygame.time.Clock()

        ### Init pymunk and create space
        self.space = pymunk.Space()
        self.space.gravity = (0.0, -900.0)
        ### ground
        body = pymunk.Body()
        shape = pymunk.Segment(body, (50, 100), (550, 100), .0)
        shape.friction = 1.0
        self.space.add(shape)

        ### pyramid
        x = Vec2d(-100, 7.5) + (300, 100)
        y = Vec2d(0, 0)
        deltaX = Vec2d(0.5625, 2.0) * 10
        deltaY = Vec2d(1.125, 0.0) * 10

        for i in range(25):
            y = Vec2d(x)
            for j in range(i, 25):
                size = 5
                points = [(-size, -size), (-size, size), (size, size),
                          (size, -size)]
                mass = 1.0
                moment = pymunk.moment_for_poly(mass, points, (0, 0))
                body = pymunk.Body(mass, moment)
                body.position = y
                shape = pymunk.Poly(body, points, (0, 0))
                shape.friction = 1
                self.space.add(body, shape)

                y += deltaY

            x += deltaX
コード例 #10
0
    def carry_element(self, element, __dt=None):
        if time.time() - element.released_at < 1.0:
            return True
        # move element to "carried elements layer"
        element.shape.layers = defs.CARRIED_THINGS_LAYER

        # bind it to wizard
        # #move element up
        pivot = self.body.position + Vec2d(defs.wizard_hand)
        element.body.position = pivot
        element.joint(self, pivot)

        self.carried_elements.append(element)
        element.wizard = self
コード例 #11
0
    def replace_objs(self, As, BClass, *Bargs, **Bkwargs):
        massum = 0.0
        momentum = Vec2d(0, 0)
        for x in As:
            massum += x.body.mass
            momentum += x.body.velocity * x.body.mass
            Logger.debug("momentum is %s after adding mass=%s vel=%s",
                         momentum, x.body.velocity, x.body.mass)
            self.remove_obj(x)
        Bkwargs['pos'] = As[0].pos
        Bkwargs['size'] = As[0].size
        Bkwargs['momentum'] = momentum / len(
            As)  # I have no idea why I should divide it by number of As.
        #  Afair it should work well without dividing,

        self.schedule_add_widget(BClass, *Bargs, **Bkwargs)
コード例 #12
0
    def __init__(self, root, robot):
        self.root = root
        self.r = robot

        self.ang_vel_max = radians(30)

        self.wheel_vectors = []
        w, h = self.r.siz

        # needs to be smaller as the impulses are detected by ultrasounds
        a = 2 / 3
        w, h = [w / a, h / a]

        # wheel = [position_of_wheel, vector_when_moving_wheel_in_frontal_direction
        self.wheels = [
            [Vec2d(-w, +h), Vec2d(+1, +1)],  # lf
            [Vec2d(+w, +h), Vec2d(-1, +1)],  # rf
            [Vec2d(-w, -h), Vec2d(-1, +1)],  # lb
            [Vec2d(+w, -h), Vec2d(+1, +1)],  # rb
        ]
コード例 #13
0
ファイル: pygame_util.py プロジェクト: llfkj/cymunk
def _draw_circle(surface, circle):

    circle_center = circle.body.position + circle.offset.rotated(
        circle.body.angle)
    p = to_pygame(circle_center, surface)

    r = 0
    color = pygame.color.THECOLORS["red"]
    if circle.body.is_static:
        color = pygame.color.THECOLORS["lightgrey"]
        r = 1
    if hasattr(circle, "color"):
        color = circle.color

    pygame.draw.circle(surface, color, p, int(circle.radius), r)

    circle_edge = circle_center + Vec2d(circle.radius, 0).rotated(
        circle.body.angle)
    p2 = to_pygame(circle_edge, surface)
    line_r = 3 if circle.radius > 20 else 1
    pygame.draw.lines(surface, pygame.color.THECOLORS["blue"], False, [p, p2],
                      line_r)
コード例 #14
0
ファイル: using_sprites.py プロジェクト: llfkj/cymunk
def main():

    pygame.init()
    screen = pygame.display.set_mode((600, 600))
    clock = pygame.time.Clock()
    running = True

    ### Physics stuff
    space = pymunk.Space()
    space.gravity = Vec2d(0.0, -900.0)

    ## logo
    logo_img = pygame.image.load("pymunk_logo_googlecode.png")
    logos = []

    ### Static line
    static_body = pymunk.Body()
    static_lines = [
        pymunk.Segment(static_body, (11.0, 280.0), (407.0, 246.0), 0.0),
        pymunk.Segment(static_body, (407.0, 246.0), (407.0, 343.0), 0.0)
    ]
    for l in static_lines:
        l.friction = 0.5
    space.add(static_lines)

    ticks_to_next_spawn = 10

    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, "using_sprites.png")

        ticks_to_next_spawn -= 1
        if ticks_to_next_spawn <= 0:
            ticks_to_next_spawn = 100
            x = random.randint(20, 400)
            y = 500
            angle = random.random() * math.pi
            vs = [(-23, 26), (23, 26), (0, -26)]
            mass = 10
            moment = pymunk.moment_for_poly(mass, vs)
            body = pymunk.Body(mass, moment)
            shape = pymunk.Poly(body, vs)
            shape.friction = 0.5
            body.position = x, y
            body.angle = angle

            space.add(body, shape)
            logos.append(shape)

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

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

        for logo_shape in logos:
            # image draw
            p = logo_shape.body.position
            p = Vec2d(p.x, flipy(p.y))

            # we need to rotate 180 degrees because of the y coordinate flip
            angle_degrees = math.degrees(logo_shape.body.angle) + 180
            rotated_logo_img = pygame.transform.rotate(logo_img, angle_degrees)

            offset = Vec2d(rotated_logo_img.get_size()) / 2.
            p = p - offset

            screen.blit(rotated_logo_img, (p.x, p.y))

            # debug draw
            ps = logo_shape.get_vertices()
            ps = [(p.x, flipy(p.y)) for p in ps]
            ps += [ps[0]]
            pygame.draw.lines(screen, THECOLORS["red"], False, ps, 1)

        for line in static_lines:
            body = line.body

            pv1 = body.position + line.a.rotated(body.angle)
            pv2 = body.position + line.b.rotated(body.angle)
            p1 = pv1.x, flipy(pv1.y)
            p2 = pv2.x, flipy(pv2.y)
            pygame.draw.lines(screen, THECOLORS["lightgray"], False, [p1, p2],
                              2)

        ### Flip screen
        pygame.display.flip()
        clock.tick(50)
        pygame.display.set_caption("fps: " + str(clock.get_fps()))
コード例 #15
0
ファイル: balls_and_lines.py プロジェクト: llfkj/cymunk
def main():
            
    pygame.init()
    screen = pygame.display.set_mode((600, 600))
    clock = pygame.time.Clock()
    running = True
    
    ### Physics stuff
    space = pm.Space()
    space.gravity = Vec2d(0.0, -900.0)
    
    ## Balls
    balls = []
    
    ### Mouse
    mouse_body = pm.Body()
    mouse_shape = pm.Circle(mouse_body, 3, Vec2d(0,0))
    mouse_shape.collision_type = COLLTYPE_MOUSE
    space.add(mouse_shape)

    space.add_collision_handler(COLLTYPE_MOUSE, COLLTYPE_BALL, None, mouse_coll_func, None, None)   
    
    ### Static line
    line_point1 = None
    static_lines = []
    run_physics = True

    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, "balls_and_lines.png")
            elif event.type == MOUSEBUTTONDOWN and event.button == 1:
                p = event.pos[X], flipy(event.pos[Y])
                body = pm.Body(10, 100)
                body.position = p
                shape = pm.Circle(body, 10, (0,0))
                shape.friction = 0.5
                shape.collision_type = COLLTYPE_BALL
                space.add(body, shape)
                balls.append(shape)
                
            elif event.type == MOUSEBUTTONDOWN and event.button == 3: 
                if line_point1 is None:
                    line_point1 = Vec2d(event.pos[X], flipy(event.pos[Y]))
            elif event.type == MOUSEBUTTONUP and event.button == 3: 
                if line_point1 is not None:
                    
                    line_point2 = Vec2d(event.pos[X], flipy(event.pos[Y]))
                    print line_point1, line_point2
                    body = pm.Body()
                    shape= pm.Segment(body, line_point1, line_point2, 0.0)
                    shape.friction = 0.99
                    space.add(shape)
                    static_lines.append(shape)
                    line_point1 = None
            
            elif event.type == KEYDOWN and event.key == K_SPACE:    
                run_physics = not run_physics
        
        p = pygame.mouse.get_pos()
        mouse_pos = Vec2d(p[X],flipy(p[Y]))
        mouse_body.position = mouse_pos
        
        
        if pygame.key.get_mods() & KMOD_SHIFT and pygame.mouse.get_pressed()[0]:
            body = pm.Body(10, 10)
            body.position = mouse_pos
            shape = pm.Circle(body, 10, (0,0))
            shape.collision_type = COLLTYPE_BALL
            space.add(body, shape)
            balls.append(shape)
       
        ### Update physics
        if run_physics:
            dt = 1.0/60.0
            for x in range(1):
                space.step(dt)
            
        ### Draw stuff
        screen.fill(THECOLORS["white"])

        # Display some text
        font = pygame.font.Font(None, 16)
        text = """LMB: Create ball
LMB + Shift: Create many balls
RMB: Drag to create wall, release to finish
Space: Pause physics simulation"""
        y = 5
        for line in text.splitlines():
            text = font.render(line, 1,THECOLORS["black"])
            screen.blit(text, (5,y))
            y += 10

        for ball in balls:           
            r = ball.radius
            v = ball.body.position
            rot = ball.body.rotation_vector
            p = int(v.x), int(flipy(v.y))
            p2 = Vec2d(rot.x, -rot.y) * r * 0.9
            pygame.draw.circle(screen, THECOLORS["blue"], p, int(r), 2)
            pygame.draw.line(screen, THECOLORS["red"], p, p+p2)

        if line_point1 is not None:
            p1 = line_point1.x, flipy(line_point1.y)
            p2 = mouse_pos.x, flipy(mouse_pos.y)
            pygame.draw.lines(screen, THECOLORS["black"], False, [p1,p2])

        for line in static_lines:
            body = line.body
            
            pv1 = body.position + line.a.rotated(body.angle)
            pv2 = body.position + line.b.rotated(body.angle)
            p1 = pv1.x, flipy(pv1.y)
            p2 = pv2.x, flipy(pv2.y)
            pygame.draw.lines(screen, THECOLORS["lightgray"], False, [p1,p2])

        ### Flip screen
        pygame.display.flip()
        clock.tick(50)
        pygame.display.set_caption("fps: " + str(clock.get_fps()))
コード例 #16
0
    def goto_target(self):

        imp = (100, 100)

        rel_vec = self.camera_get_target()

        max_angle_dif = radians(10)

        def get_length(x, y):
            return sqrt(x * x + y * y)

        near_target_dist = (
            max(
                [
                    us.distance_range + get_length(*us.us_pos)
                    for us in self.ultrasounds.values()
                ]
            )
            * 1.2
        )

        close_target_dist = 3 * near_target_dist

        # print(near_target_dist, '<<<near')
        n_rel_vec = rel_vec.normalized()
        ang_vel = 0

        dets = self.ultrasound_detections()

        LR = dets == [True, False, True]
        L = dets == [True, False, False]
        R = dets == [False, False, True]
        LM = dets == [True, True, False]
        RM = dets == [False, True, True]
        M = dets == [False, True, False]
        ALL = all(dets)
        NONE = not any(dets)

        state = self.get_state(L, R, LR, LM, RM, M, ALL, NONE)
        self.add_state(state)
        # print(self.states)
        # print(self.poss)

        ALL_sum = sum(1 for s in self.states if s == "ALL")
        M_sum = sum(1 for s in self.states if s == "M")
        NONE_sum = sum(1 for s in self.states if s == "NONE")

        is_ALL = ALL_sum > self.state_count / 2
        is_M = M_sum > self.state_count / 2
        is_NONE = NONE_sum > self.state_count / 2

        if is_ALL:
            self.add_state("STUCK")
        if is_M:
            self.add_state("STUCK")

        is_stuck = "STUCK" in self.states and not "INIT" in self.states
        is_near = rel_vec.length < near_target_dist
        is_close = rel_vec.length < close_target_dist

        if is_close:
            # slow down on closing
            if not is_M and not is_ALL:
                # but not when totally obstacled around
                n_rel_vec = n_rel_vec * 0.5

        stuck_sum = 500
        sum_vec = Vec2d(0, 0)
        for p in self.poss:
            if p is not None:
                sum_vec = sum_vec + p
        # print(sum_vec)

        self.stuck_counter += int(is_stuck)
        if self.stuck_counter > 50:
            self.stuck_angle *= -1
            self.stuck_counter = 0

        if sum_vec.length < stuck_sum:
            # if not is_stuck and not is_near:
            if not is_near:
                if not is_NONE:
                    self.add_state("STUCK")
        #   else:
        #      self.stuck_angle *= -1
        # self.stuck_rel_vec = rel_vec
        # self.stuck_rel_vec.rotate(self.stuck_angle)

        assert len(dets) == 3
        # if us_count is not 3, following algorithm may missbehave

        is_stuck = "STUCK" in self.states and not "INIT" in self.states

        if is_stuck and not is_near:
            # rel_vec = self.stuck_rel_vec
            rel_vec.rotate_degrees(self.stuck_angle)

        if abs(rel_vec.angle) > max_angle_dif:
            ang_vel = -(rel_vec.angle) * 1

        if is_stuck:
            vel_vec = n_rel_vec
            self.control.go(vel_vec, ang_vel, self.stuck_angle)
            return

        if is_near:
            ang_vel = ang_vel * 5.5
            vel_vec = n_rel_vec * 0.5
            self.control.go(vel_vec, ang_vel)
        else:
            vel_vec = n_rel_vec
            if NONE or LR:
                self.control.go(vel_vec, ang_vel)
            elif ALL or M:
                # self.control.go(vel_vec, ang_vel, 'br')
                # self.control.go(Vec2d(0,0), 10)
                self.control.go(vel_vec, ang_vel, "right")
                return
            elif L or LM:
                self.control.go(vel_vec, ang_vel, "right")
                return
            elif R or RM:
                self.control.go(vel_vec, ang_vel, "left")
                return
コード例 #17
0
ファイル: pyglet_util.py プロジェクト: llfkj/cymunk
def _draw_circle(circle, batch = None):
    circle_center = circle.body.position + circle.offset.rotated(circle.body.angle)
    
    r = 0
    if hasattr(circle, "color"):
        color = circle.color  
    elif circle.body.is_static:
        color = (200, 200, 200)
        r = 1
    else:
        color = (255, 0, 0)
        
    #http://slabode.exofire.net/circle_draw.shtml
    num_segments = int(4 * math.sqrt(circle.radius))
    theta = 2 * math.pi / num_segments
    c = math.cos(theta)
    s = math.sin(theta)
    
    x = circle.radius # we start at angle 0
    y = 0
    
    ps = []
    
    for i in range(num_segments):
        ps += [Vec2d(circle_center.x + x, circle_center.y + y)]
        t = x
        x = c * x - s * y
        y = s * t + c * y
               
    
    if circle.body.is_static:
        mode = pyglet.gl.GL_LINES
        ps = [p for p in ps+ps[:1] for _ in (0, 1)]
    else:
        mode = pyglet.gl.GL_TRIANGLE_STRIP
        ps2 = [ps[0]]
        for i in range(1, int(len(ps)+1/2)):
            ps2.append(ps[i])
            ps2.append(ps[-i])
        ps = ps2
    vs = []
    for p in [ps[0]] + ps + [ps[-1]]:
            vs += [p.x, p.y]
        
    c = circle_center + Vec2d(circle.radius, 0).rotated(circle.body.angle)
    cvs = [circle_center.x, circle_center.y, c.x, c.y]
        
    bg = pyglet.graphics.OrderedGroup(0)
    fg = pyglet.graphics.OrderedGroup(1)
        
    l = len(vs)//2
    if batch == None:
        pyglet.graphics.draw(l, mode,
                            ('v2f', vs),
                            ('c3B', color*l))
        pyglet.graphics.draw(2, pyglet.gl.GL_LINES,
                            ('v2f', cvs),
                            ('c3B', (0,0,255)*2))
    else:
        batch.add(len(vs)//2, mode, bg,
                 ('v2f', vs),
                 ('c3B', color*l))
        batch.add(2, pyglet.gl.GL_LINES, fg,
                 ('v2f', cvs),
                 ('c3B', (0,0,255)*2))
    return
コード例 #18
0
ファイル: point_query.py プロジェクト: llfkj/cymunk
def main():
    pygame.init()
    screen = pygame.display.set_mode((600, 600))
    clock = pygame.time.Clock()
    running = True
    
    ### Physics stuff
    space = pm.Space()
    space.gravity = Vec2d(0.0, -900.0)
    
    ## Balls
    balls = []
       
    ### walls
    static_lines = [pm.Segment(space.static_body, Vec2d(111.0, 280.0), Vec2d(407.0, 246.0), 1.0)
                    ,pm.Segment(space.static_body, Vec2d(407.0, 246.0), Vec2d(407.0, 343.0), 1.0)
                    ]    
    space.add(static_lines)
    
    ticks_to_next_ball = 10


    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, "point_query.png")
                
        ticks_to_next_ball -= 1
        if ticks_to_next_ball <= 0:
            ticks_to_next_ball = 100
            mass = 10
            radius = 25
            inertia = pm.moment_for_circle(mass, 0, radius, Vec2d(0,0))
            body = pm.Body(mass, inertia)
            x = random.randint(115,350)
            body.position = x, 400
            shape = pm.Circle(body, radius, Vec2d(0,0))
            #shape.color = THECOLORS["lightgrey"]
            space.add(body, shape)
            balls.append(shape)
        
        ### Clear screen
        screen.fill(THECOLORS["white"])
        
        ### Draw stuff
        pygame_util.draw(screen, space)
        
        balls_to_remove = []
        for ball in balls:
            if ball.body.position.y < 200: balls_to_remove.append(ball)

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

        mouse_pos = pygame_util.get_mouse_pos(screen)

        shape = space.point_query_first(Vec2d(mouse_pos))
        if shape is not None:
            if hasattr(shape, "radius"):
                r = shape.radius + 4
            else:
                r = 10
            p = pygame_util.to_pygame(shape.body.position, screen)
            pygame.draw.circle(screen, THECOLORS["red"], p, int(r), 2)
        
        ### Update physics
        dt = 1.0/60.0
        for x in range(1):
            space.step(dt)
        
        
        
        ### Flip screen
        pygame.display.flip()
        clock.tick(50)
        pygame.display.set_caption("fps: " + str(clock.get_fps()))
コード例 #19
0
def main():
    ### PyGame init
    pygame.init()
    screen = pygame.display.set_mode((width, height))
    clock = pygame.time.Clock()
    running = True
    font = pygame.font.SysFont("Arial", 16)

    ### Physics stuff
    space = pymunk.Space()
    space.gravity = 0, -1000
    # walls - the left-top-right walls
    static = [
        pymunk.Segment(space.static_body, (50, 50), (50, 550), 5),
        pymunk.Segment(space.static_body, (50, 550), (650, 550), 5),
        pymunk.Segment(space.static_body, (650, 550), (650, 50), 5),
        pymunk.Segment(space.static_body, (50, 50), (650, 50), 5)
    ]

    b2 = pymunk.Body()
    static.append(pymunk.Circle(b2, 30))
    b2.position = 300, 400

    for s in static:
        s.friction = 1.
        s.group = 1
    space.add(static)

    # "Cannon" that can fire arrows
    cannon_body = pymunk.Body()
    cannon_shape = pymunk.Circle(cannon_body, 25)
    cannon_shape.sensor = True
    cannon_body.position = 100, 100
    space.add(cannon_shape)

    arrow_body, arrow_shape = create_arrow()
    space.add(arrow_shape)

    space.add_collision_handler(0, 1, post_solve=post_solve_arrow_hit)

    flying_arrows = []

    while running:
        for event in pygame.event.get():
            if event.type == QUIT or \
                event.type == KEYDOWN and (event.key in [K_ESCAPE, K_q]):
                running = False
            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                start_time = pygame.time.get_ticks()
            elif event.type == KEYDOWN and event.key == K_p:
                pygame.image.save(screen, "arrows.png")
            elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
                end_time = pygame.time.get_ticks()

                diff = end_time - start_time
                power = max(min(diff, 1000), 10) * 1.5
                impulse = Vec2d(1, 0) * power
                arrow_body.apply_impulse(impulse.rotated(arrow_body.angle))

                space.add(arrow_body)
                flying_arrows.append(arrow_body)

                arrow_body, arrow_shape = create_arrow()
                space.add(arrow_shape)

        keys = pygame.key.get_pressed()

        speed = 2.5
        if (keys[K_UP]):
            cannon_body.position += Vec2d(0, 1) * speed
        if (keys[K_DOWN]):
            cannon_body.position += Vec2d(0, -1) * speed
        if (keys[K_LEFT]):
            cannon_body.position += Vec2d(-1, 0) * speed
        if (keys[K_RIGHT]):
            cannon_body.position += Vec2d(1, 0) * speed

        mouse_position = from_pygame(Vec2d(pygame.mouse.get_pos()), screen)
        cannon_body.angle = Vec2d(mouse_position - cannon_body.position).angle
        # move the unfired arrow together with the cannon
        arrow_body.position = cannon_body.position + Vec2d(
            cannon_shape.radius + 40, 0).rotated(cannon_body.angle)
        arrow_body.angle = cannon_body.angle

        for flying_arrow in flying_arrows:
            drag_constant = 0.0002
            pointing_direction = Vec2d(1, 0).rotated(flying_arrow.angle)
            flight_direction = Vec2d(flying_arrow.velocity)
            flight_speed = flight_direction.normalize_return_length()
            dot = flight_direction.dot(pointing_direction)
            # (1-abs(dot)) can be replaced with (1-dot) to make arrows turn around even when fired straight up.
            # Might not be as accurate, but maybe look better.
            drag_force_magnitude = (
                1 -
                abs(dot)) * flight_speed**2 * drag_constant * flying_arrow.mass

            arrow_tail_position = Vec2d(-50, 0).rotated(flying_arrow.angle)
            flying_arrow.apply_impulse(
                -flight_direction * drag_force_magnitude, arrow_tail_position)

            flying_arrow.angular_velocity *= 0.9
        for cb in callbacks:
            cbf = cb[0]
            params = cb[1:]
            cbf(*params)
        del callbacks[:]

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

        ### Draw stuff
        draw(screen, space)

        # Power meter
        if pygame.mouse.get_pressed()[0]:
            current_time = pygame.time.get_ticks()
            diff = current_time - start_time
            power = max(min(diff, 1000), 10)
            h = power / 2
            pygame.draw.line(screen, pygame.color.THECOLORS["red"], (30, 550),
                             (30, 550 - h), 10)

        # Info and flip screen
        screen.blit(
            font.render("fps: " + str(clock.get_fps()), 1, THECOLORS["white"]),
            (0, 0))
        screen.blit(
            font.render("Aim with mouse, hold LMB to powerup, release to fire",
                        1, THECOLORS["darkgrey"]), (5, height - 35))
        screen.blit(
            font.render("Press R to reset, ESC or Q to quit", 1,
                        THECOLORS["darkgrey"]), (5, height - 20))

        pygame.display.flip()

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

        clock.tick(fps)
コード例 #20
0
 def __init__(self, *a, **kw):
     super(Wizard, self).__init__(*a, mass=defs.wizard_mass, **kw)
     self.layers = defs.NORMAL_LAYER
     self.carried_elements = []
     self.touching_elements = []
     self.applied_force = Vec2d(0, 0)
コード例 #21
0
import cymunk as pymunk
from cymunk import Vec2d

window = pyglet.window.Window(width=600, height=600)

fps_display = pyglet.clock.ClockDisplay()

logo_img = pyglet.resource.image('pymunk_logo_googlecode.png')
logo_img.anchor_x = logo_img.width / 2
logo_img.anchor_y = logo_img.height / 2
logos = []
batch = pyglet.graphics.Batch()

### Physics stuff
space = pymunk.Space()
space.gravity = Vec2d(0.0, -900.0)

### Static line
static_body = pymunk.Body()
static_lines = [
    pymunk.Segment(static_body, (11.0, 280.0), (407.0, 246.0), 0.0),
    pymunk.Segment(static_body, (407.0, 246.0), (407.0, 343.0), 0.0)
]
for l in static_lines:
    l.friction = 0.5
space.add(static_lines)


@window.event
def on_key_press(symbol, modifiers):
    if symbol == pyglet.window.key.P:
コード例 #22
0
ファイル: spiderweb.py プロジェクト: avsaj/cymunk
dist = .3

cb = pymunk.Body(1,1)
cb.position = c
s = pymunk.Circle(cb, 15) # to have something to grab
s.group = web_group
s.layers = web_layers
s.collision_type = web_collision_type
#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) 
コード例 #23
0
import math, random

import pyglet

import cymunk as pymunk
from cymunk import Vec2d
from pyglet_util import draw

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.)

### CONTAINER
ss = [
    pymunk.Segment(space.static_body, (0, 0), (window.width, 0), 5),
    pymunk.Segment(space.static_body, (window.width, 0),
                   (window.width, window.height), 5),
    pymunk.Segment(space.static_body, (window.width, window.height),
                   (0, window.height), 5),
    pymunk.Segment(space.static_body, (0, window.height), (0, 0), 5)
]

for s in ss:
    s.friction = .5
    s.layers = s.layers ^ 0b100