我正在尝试创建3D动画,每个球体都沿随机方向(向上,向下,向左,向右,向后或向前)移动。它们都在3D世界中移动(每个球体都有随机的X,Y和Z值),并且投影在2D屏幕上。我期望每个球体在随机方向上独立于其他球体而运动,但这些球体似乎完全在一个方向上运动,如下所示。
鉴于我的代码,我不明白为什么它会这样工作:
# random X, Y, Z: fill X, Y and Z coordinates with uniform random values that serve as coordinates
for sphere in spheres:
sphere.position.xy = np.random.uniform(-20, 20, size=2)
sphere.position.z = np.random.uniform(z_near, z_far)
# Create two angles for each sphere, theta and phi, to compute the change of direction.
sphere.theta_deg = np.random.rand(1) * 360; # Angle thera controls the horizontal orientation of the gaze.
sphere.phi_deg = np.random.rand(1) * 360; # Angle Phi controls the vertical orientation of the gaze.
# Different directions
speed = 3; #degrees/seconds
theta_rad = sphere.theta_deg * np.pi /180; #direction converted to radians
phi_rad = sphere.phi_deg* np.pi /180; #direction converted to radians
dx = speed*np.sin(-phi_rad-theta_rad)/frameRate;
dy = -speed*np.cos(phi_rad + theta_rad)/frameRate;
dz = -speed*np.cos(theta_rad)/frameRate;
while 1:
# Modulate the angular directions
dx = speed*np.sin(-phi_rad-theta_rad)/frameRate;
dy = -speed*np.cos(phi_rad + theta_rad)/frameRate;
dz = -speed*np.cos(theta_rad)/frameRate;
for sphere in spheres:
# Update Spheres Positions
sphere.position.x += dx
sphere.position.y += dy
sphere.position.z += dz
球体位置应该在每帧更新,并且应该是随机的。
非常感谢您的帮助!
在while
循环之前,程序从theta_rad
列表中最后一个球体的phi_rad
和theta_deg
值中计算出一个phi_deg
和一个spheres
。然后,它使用该theta_rad
和phi_rad
来计算单个dx
,单个dy
和单个dz
。然后,它使用for
循环将这些dx
,dy
和dz
值应用于列表中的每个球体。列表中的所有球体都获得完全相同的增量,这就是为什么它们都沿相同方向移动的原因。
((程序每次通过dx
循环时,也会重新计算完全相同的dy
,dz
和while
值。这不会造成任何额外的损害,只是没有意义。)
[要解决,您需要为每个单独的球体分别计算theta_rad
和phi_rad
值(基于每个球体的唯一theta_deg
和phi_deg
属性);您需要使用每个球面的theta_rad
和phi_rad
值来为每个球面分别计算dx
,dy
和dz
值;并且您需要将每个球体的dx
,dy
和dz
值存储为该球体的属性。
然后每次在while
循环周围,您将通过添加该球体自己的position.x
,position.y
和position.z
值来调整每个球体的dx
,dy
和dz
。
您可以进行所有额外的按球计算并存储在第一个for
循环中。它将变成这样:
speed = 3 # define this before the 'for' loop so that we can use it inside the loop
for sphere in spheres:
sphere.position.xy = np.random.uniform(-20, 20, size=2)
sphere.position.z = np.random.uniform(z_near, z_far)
sphere.theta_deg = np.random.rand(1) * 360
sphere.phi_deg = np.random.rand(1) * 360
theta_rad = sphere.theta_deg * np.pi / 180
phi_rad = sphere.phi_deg* np.pi / 180
sphere.dx = speed * np.sin(-phi_rad - theta_rad) / frameRate
sphere.dy = -speed * np.cos(phi_rad + theta_rad) / frameRate
sphere.dz = -speed * np.cos(theta_rad) / frameRate
基本上,您的while循环将变得更加简单:
while 1:
for sphere in spheres:
sphere.position.x += sphere.dx
sphere.position.y += sphere.dy
sphere.position.z += sphere.dz