3D动画中每个球体的随机方向

问题描述 投票:1回答:1

我正在尝试创建3D动画,每个球体都沿随机方向(向上,向下,向左,向右,向后或向前)移动。它们都在3D世界中移动(每个球体都有随机的X,Y和Z值),并且投影在2D屏幕上。我期望每个球体在随机方向上独立于其他球体而运动,但这些球体似乎完全在一个方向上运动,如下所示。enter image description here

鉴于我的代码,我不明白为什么它会这样工作:

# 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

球体位置应该在每帧更新,并且应该是随机的。

非常感谢您的帮助!

python animation 3d
1个回答
0
投票

while循环之前,程序从theta_rad列表中最后一个球体的phi_radtheta_deg值中计算出一个phi_deg和一个spheres。然后,它使用该theta_radphi_rad来计算单个dx,单个dy和单个dz。然后,它使用for循环将这些dxdydz值应用于列表中的每个球体。列表中的所有球体都获得完全相同的增量,这就是为什么它们都沿相同方向移动的原因。

((程序每次通过dx循环时,也会重新计算完全相同的dydzwhile值。这不会造成任何额外的损害,只是没有意义。)

[要解决,您需要为每个单独的球体分别计算theta_radphi_rad值(基于每个球体的唯一theta_degphi_deg属性);您需要使用每个球面的theta_radphi_rad值来为每个球面分别计算dxdydz值;并且您需要将每个球体的dxdydz值存储为该球体的属性。

然后每次在while循环周围,您将通过添加该球体自己的position.xposition.yposition.z值来调整每个球体的dxdydz

您可以进行所有额外的按球计算并存储在第一个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
© www.soinside.com 2019 - 2024. All rights reserved.