split gravitational force into x, y, and z componenets I am writing a program for a computer science class in which I am doing an n-body simulation in 3-dimensional space. Currently, I have figured out the gravitational force along the hypotenuse between two bodies. Now I have to split these up into the x, y, and z components, and this is where I am having trouble.
Force between two objects (force_t)=G*m1*m2/r^2
Typically, force_x=force_t*cos(angle between x-axis and hypotenuse)
force_y=force_t*sin(angle between x-axis and hypotenuse)
So, I can figure out my triangle. I know that my two bodies are located at (x1, y1, z1) and (x2, y2, z2), so I have my triangle. And I am fairly certain that the above equations will hold for x and y, even though I'm in three dimensions, but I'm just not sure what the corresponding equation for the z component will be. My thought was that the combination of the three forces has to equal the total force, so perhaps I solve for the z component algebraically using the pythagorean theorem, but I have no way to check whether or not this is true.
Anyway, any help would be appreciated. Thanks!
 A: For this application, I'd suggest using the actual gravitational force equation, for vector quantities:
$$\vec{F} = \frac{Gm_1m_2}{r^3}\vec{r}$$
Here $\vec{r}$ is the vector pointing from the source object to the point where you are computing the force. So if you're computing the force on object 2 (caused by object 1), you'll have
$$\vec{r} = (x_2 - x_1, y_2 - y_1, z_2 - z_1)$$
or if you're computing the force on object 1 (caused by object 2), it'll be the other way around,
$$\vec{r} = (x_1 - x_2, y_1 - y_2, z_1 - z_2)$$
Since the force equation is a vector equation, you effectively get one copy of it for each of the three directions,
$$\begin{align}F_x &= \frac{Gm_1m_2}{r^3}r_x \\ F_y &= \frac{Gm_1m_2}{r^3}r_y \\ F_z &= \frac{Gm_1m_2}{r^3}r_z\end{align}$$

As a side note:

Typically, force_x=force_t*cos(angle between x-axis and hypotenuse)
force_y=force_t*sin(angle between x-axis and hypotenuse)

Those equations do not generally hold in 3D. Or rather, the first one does, but not the second one. The general rule is
$$F_s = |\vec{F}|\cos\bigl(\theta_{s,F}\bigr)$$
which means that the $s$-component of force ($F_s$), where $s$ can represent any axis, is equal to the magnitude of the force ($|\vec{F}|$) times the cosine of the angle between the force and the axis [$\cos(\theta_{s,F})$].
In the particular case of 2D space, the angle between the force and the x-axis is the complement of the angle between the force and the y-axis: $\theta_{y,F} = 90^\circ - \theta_{x,F}$. And since $\cos(90^\circ - \theta) = \sin\theta$ (in 2D only), you can replace $\cos(\theta_{y,F})$ with $\sin(\theta_{x,F})$.
A: Use $F_x = -x GmM/|r|^3$, similar for $y$ and $z$. This is obtained by taking $F=GmM/|r|^2$ where the direction is $-\hat{r} = -\vec{r}/|r| = -(x,y,z)/|r|$, so the $x$-component is $-x/|r|$.
In the above, $|r| = \sqrt{x^2+y^2+z^2}$.
