简体   繁体   中英

Slinky in VPython

The goal of the VPython code below is to model a slinky using 14 balls to represent the broken-down components of the slinky. But I am facing some problems with my code. For instance,

R[i] = ball[i].pos - ball[i+1].pos

raises

'int' object has no attribute 'pos'

What is the meaning of the above error?

This is my program:

from __future__ import print_function, division
from visual import *

ceiling = box(pos=(0,0,0), size=(0.15, 0.015, 0.15), color=color.green)

n = 14 #number of "coils" (ball objects)
m = 0.015 #mass of each ball; the mass of the slinky is therefore m*n

L = 0.1  #length of the entire slinky
d = L/n #a starting distance that is equal between each

k = 200 #spring constant of the bonds between the coils


t = 0
deltat = 0.002
g = -9.8
a = vector(0,g,0)


ball=[28]
F=[]
R=[]

#make 28 balls, each a distance "d" away from each other

for i in range(n):
    ball = ball+[sphere(pos=vector(0,-i*d,0), radius = 0.005, color=color.white)]
    #ball[i].p = vector(0,0,0)
for i in range(n-1):
    F.append(vector(0,0,0))
    R.append(vector(0,0,0))


#calculate the force on each ball and update its position as it falls

while t < 5:
    rate(200)
    for i in range (n-1):
        R[i]=ball[i].pos-ball[i+1].pos
        F[i]=200*(mag(R[i]) - d)*norm(R[i])
        #r[i] = ball[i].pos - ball[i+1].pos
        #F[i] = 200*((r[i].mag - d)*((r[i])/(r[i].mag)))
    for i in range(n-1):
        ball[i+1].p = ball[i+1].p + (F[i] - F[i+1] + (0.015*a))*deltat
        ball[i+1].pos = ball[i+1].pos + ((ball[i+1].p)/0.015)*deltat
        t = deltat + t

It looks like you've assigned an int value to ball[i] object. With that in mind, the error message is pretty clear: an integer object doesn't have an attribute .pos (which belongs to the sphere class.

If you expect ball to be a list of sphere objects, you need to do something differently. Currently you've initialized ball = [28] , which is a list with a single element, integer value 28.

So, where i = 0, ball[i] returns 28 , which obviously doesn't have any such attribute of a sphere.

This might do it:

ball=[]  ### initialize ball as an empty list
F=[]
R=[]

#make 28 balls, each a distance "d" away from each other
"""
    You said you want only 14 balls, but the comment above says 28...
"""

for i in range(n):
    ball.append(sphere(pos=vector(0,-i*d,0), radius = 0.005, color=color.white))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM