pygame和pymunk制作的单摆示例程序

"""pygame和pymunk制作的单摆示例程序"""

import sys
import random
import pygame
import pymunk
import pymunk.pygame_util
from pygame.locals import *

# 新建屏幕
size = width,height = 600,600
pygame.init()
screen = pygame.display.set_mode(size)
pygame.display.set_caption("单摆测试,Simple pendulum test by lixingqiu")

# 重力空间
space = pymunk.Space()
space.gravity = (0.0, -2000.0)

center_x = width // 2
center_y = height //2
mass = 10                               # 球的质量
radius = 25                             # 球的半径
moment = pymunk.moment_for_circle(mass, radius ,radius )
body = pymunk.Body(mass, moment)
body.position = (center_x,center_y-125)

shape = pymunk.Circle(body, radius)
shape.elasticity = 0.9999999
space.add(body, shape)

print(help(pymunk.PinJoint))
"""
 __init__(self, a, b, anchor_a=(0, 0), anchor_b=(0, 0))
 |      a and b are the two bodies to connect, and anchor_a and anchor_b are
 |      the anchor points on those bodies.
 |      
 |      The distance between the two anchor points is measured when the joint
 |      is created. If you want to set a specific distance, use the setter
 |      function to override it.
前面这个参数space.stacic_body相当于固定点,后面这个body是小球。
第三个参数,就是anchor_a,相当于固定点的坐标。
第四个参数,就是anchor_b,是第二个描点,它连接球,坐标是偏移量。

"""
pj = pymunk.PinJoint(space.static_body, body, (center_x,center_y+125), (0,0))
space.add(pj)

draw_options = pymunk.pygame_util.DrawOptions(screen) # 设定space内物体的渲染面

body.force=(100000,0)              # 给力
running = True

clock = pygame.time.Clock()
while running:
    for event in pygame.event.get():
        if event.type in( QUIT,KEYDOWN,K_ESCAPE):
            running = False
            break         

    space.step(1/50.0)

    screen.fill((255,255,255))        
    space.debug_draw(draw_options)  # 重画重力空间内的shape
 
    pygame.display.flip()
    clock.tick(50)

pygame.quit()

 

单摆测试,Simple pendulum test by lixingqiu