Tuesday, May 10, 2016

N-Spring System

 Using Visual Python

 I like the result, :)

#code
from visual import *

n       = 13
display(center=(n/2,0,0),background=(1,1,1), autoscale=False, range=(7),        
        width=600, height=600,  forward=(-.4,-.3,-1)) #arah kamera

distant_light(direction=(1,1,1), color=color.orange)
dt      = 1./8.
dx      = []
k       = []
m       = []
l0      = []
l       = []
v       = []
x       = []
for i in arange(n):
    dx.append(.1)
    k.append(1.)
    m.append(1.)
    l0.append(1.)
    l.append(1.)
    v.append(0.)
    x.append(0.)
pegas   = []
kotak   = []

for i in arange(n):
    spring  = helix(pos=(0,0,0), axis=(5,0,0), radius=0.2, color=color.red, length=1.)
    pegas.append(spring)
    ko      =  box(pos=(0,0,0), width=.5, height=.5, length= .5, color= color.green)
    kotak.append(ko)

box(pos=(-1,.64,0), width=n, height=2, length= 2, color=color.black)
box(pos=(n/2.,-.36,0), width=n, height=.2, length= n, color=color.white,opacity=.9)

#usikan
l[0]        = 1.2 
l[n-1]      = .9
#posisi x
position    = 0
for i in arange(n):
    position    +=l[i]
    x[i]        = position
    kotak[i].x  = x[i]


def updatePegas():
    global l
    for i in arange(n):
        if i!=0:
            pegas[i].x  = x[i-1]
            l[i]        = x[i]-x[i-1]
        else:
            l[i]        = x[i]

        kotak[i].x      = x[i]
        pegas[i].length = l[i]
        
def proses():
    for i in arange(n):
        dx[i]   = l[i]-l0[i]
        f0      = -k[i]*dx[i]
        if i<n-1:
            dx[i+1] = l[i+1]-l0[i+1]
            f1      = -k[i+1]*dx[i+1]
            a       = (f0-f1)/m[i]
        else:
            a       = f0/m[i]
        v[i]    += a*dt
        x[i]    += v[i]*dt
    updatePegas()
while 1:
    rate (19)
    proses()

.