pymunk物理引擎基本例子

"""pymunk物理引擎基本例子
"""
import turtle
import pymunk
import pymunk.util
from pymunk import Vec2d
import math, sys, random

def main():
              
    space = pymunk.Space()
    space.gravity = (0.0, -900.0)
    
    ## Balls
    balls = []
    balls_for_render = []
          
    ticks_to_next_ball = 10
    for x in range(5008880):            
        ticks_to_next_ball -= 1
        if ticks_to_next_ball <= 0:
            ticks_to_next_ball = 10000
            mass = 10
            radius = 25
            inertia = pymunk.moment_for_circle(mass, 0, radius, (0,0))
            body = pymunk.Body(mass, inertia)
            x = random.randint(-200,200)
            body.position = x, 400
            shape = pymunk.Circle(body, radius, Vec2d(0,0))
            
            space.add(body, shape)
            balls.append(shape)
            # 以下代码是lixingqiu加的
            b = turtle.Turtle(visible=False,shape='circle')
            b.penup()
            b.shapesize(radius/10,radius/10) # 海龟画图中小球默认半径为10
            b.goto(x, 400)
            b.showturtle()
            balls_for_render.append(b)
        
        
        balls_to_remove = []
        
        for i in range(len(balls)):
            ball = balls[i]
            if ball.body.position.y < 0:
                balls_to_remove.append(i)# 加到待移除列表
            b = balls_for_render[i]
            b.goto(ball.body.position)
                
        for i in balls_to_remove:
            space.remove(balls[i], balls[i].body)
            balls.pop(i)            
            balls_for_render.pop(i)

        if len(balls) >= 1:
           v = balls[0].body.position
           print("(in on_draw): point = %.2f, %.2f" % (v.x,v.y))

        ### Update physics
        for x in range(1):
            space.step(1/50.0)
        

if __name__ == '__main__':
    width,height = 600,600
    screen = turtle.Screen()
    screen.delay(0)
    screen.setup(width,height)
    screen.title("pymunk物理引擎基本例子")
    
    sys.exit(main())

 

本站所有作品,教程等皆为原创,盗版必究。一旦付款,表示同意本站知识付费原则:数字商品,不支持退款。扫码付款后的朋友可以加QQ: 406273900,提供技术支持及发送作品图片与配音素材。亦可直接向微信号scratch8付款购买。
李兴球的博客_Python创意编程技术前沿 » pymunk物理引擎基本例子

学本领,探索更大的世界!

李兴球博客 风火轮编程主页