简体   繁体   English

VPython中的Slinky

[英]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. 下面的VPython代码的目标是使用14个球来表示一个Slinky,以表示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' 'int'对象没有属性'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. 好像您已经为ball[i]对象分配了一个int值。 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. 考虑到这一点,错误消息非常清楚:一个整数对象没有属性.pos (属于sphere类。

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. 当前,您已初始化ball = [28] ,这是一个包含单个元素的列表 ,整数值为28。

So, where i = 0, ball[i] returns 28 , which obviously doesn't have any such attribute of a sphere. 因此,在i = 0的情况下, ball[i]返回28 ,这显然不具有任何这样的球体属性。

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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