我正在尝试创建一个 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
属性);你需要使用那些per-sphere theta_rad
和phi_rad
单独计算的值 dx
, dy
和dz
每个领域的值(value)观;你需要存储这些每个球体 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
关于python - 3D 动画中每个球体的随机方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58611635/