PYTHON程式語言的學習-10

在這個講次當中我們學習如何使用VPYTHON模組來模擬動畫。


VYTHON的動畫模擬功能1


利用rate(10)這個指令我們可以在一秒鐘之內做10次計算,也就是每0.1秒計算一次。這個計算剛好與我們所設定的時間差0.1秒是吻合的,表示這個模擬是一個即時的模擬,不會用快動作播放,也不會用慢動作播放模擬。

VYTHON的動畫模擬-1(10個子彈)



from visual import *
scene = display(width=800, height=800,center=(1, 1, 0),
                background=(0.5,0.5,0))
Xaxis=arrow(pos=(-10,0,0), axis=(20,0,0), shaftwidth=0.05, color=(1,0,0))
#下面這個指令定義的10個球代表10個子彈
balls = [sphere(pos=(-8,0,0), radius = 0.4, color=color.yellow) for i in range(10)]
ring1=ring(pos=(4,0,0), radius=1, width=0.1)  #子彈穿越過的圓環
#一圓柱體來代表發射子彈的槍
gun=cylinder(radius=0.5,pos=(-10,0,0),axis=(2,0,0), color=color.blue)
t=0.;  dt=0.1; v=1.
while t<20.:
    rate(10)  #rate這個函數控制我們1秒鐘要計算幾次
    t=t+dt           #系統的時間t隨著while迴圈而陸續增加,每次e迴圈增加dt
    for i in range(10):
        if(t<2*i): break  #i是球的指標,假如時間未到達2*i之前這顆球停止不動
        x=balls[i].pos.x+v*dt #否則就進行等速度運動x=v*t or x=x+v*dt
        balls[i].pos=vector(x,0,0) #把新的位置座標向量vector賦予球的位置ball.pos





四個進行軌道運動的球


一個物體如果在一個特定的軌道上運動,只要我們能夠描述出這個軌道的參數方程式,並且將參數t指定為時間,就可以把物體按照時間的增加,而在軌道上不同的位置呈現出來,就成為我們所需要的動畫模擬。在下面的計算機程式當中我們試圖用make_trail=True的指令來呈現出物體運動的軌跡。這4個物體運動的軌跡分別有圓,橢圓和一維簡諧運動。我們並且強調角速率(\(\omega\), angular velocity)所扮演的角色。

四個進行軌道運動的球



from visual import *
scene = display(width=800, height=800,center=(1, 1, 0),
                background=(0.5,0.5,0))
Xaxis=arrow(pos=(0,0,0), axis=(10,0,0), shaftwidth=0.1, color=(1,0,0))
Yaxis=arrow(pos=(0,0,0), axis=(0,10,0), shaftwidth=0.05, color=(1,0,1))
ball1 = sphere(pos=(2,0,0), radius = 0.4, color=color.yellow, make_trail=True)
ball2 = sphere(pos=(3,0,0), radius = 0.4, color=color.red, make_trail=True)
ball3 = sphere(pos=(7,0,0), radius = 0.4, color=color.blue, make_trail=True)
ball4 = sphere(pos=(8,0,0), radius = 0.4, color=color.black, make_trail=True)
t=0.;     #初始時間歸零
dt=0.1;   #時間的微量間隔
r=2.;     #半徑
w=1.      #角速率
while t<20.:
    rate(10)
    t=t+dt   
    ball1.pos=vector(2.*cos(w*t),2.*sin(w*t),0) #時間增加球的位置也跟隨改變
    ball2.pos=vector(3.*cos(0.5*w*t),3.*sin(0.5*w*t),0)
    ball3.pos=vector(7.*cos(w*t),4.*sin(w*t),0)
    ball4.pos=vector(8,4.*sin(w*t),0)