计算 3d 中力的方向

Compute the direction of the force in 3d

我正在尝试构建太阳系的 3D 模拟,但我很难找到此 2D python 代码的 3D 等价物

# Compute the force of attraction f = G * self.mass * other.mass / (d**2)

# Compute the direction of the force.
    theta = math.atan2(dy, dx)
    fx = math.cos(theta) * f
    fy = math.sin(theta) * f
    return fx, fy

二维码效率低得离谱。您根本不需要任何三角函数。它只是将力的大小 f 乘以 (dx, dy) 方向上的单位向量。鉴于您已经知道向量的长度,d,您只需要

fx, fy = f*dx/d, f*dy/d

在 3-D 中

fx, fy, fz = f*dx/d, f*dy/d, f*dz/d