I'm trying to create a simple program that simulates gravity. The idea is that I have one central sun and several planets that I can create with a swipe gesture on the screen, and I use the initial swipe to provide the planets with an initial velocity.
After some time the planet will eventually start to move around the sun according to Newton's law.
My current approach is: At any moment I compute the value of the gravitational force that the sun exerts on the planet ($Mp$ is the mass of the planet and $Ms$ is the mass of the sun):
$$F = G \frac{Mp Ms}{r^2}$$
Then I find the acceleration value for the planet with
$$A = \frac{F}{Mp}$$
Then I find the angle, $\theta$, of the line that connects the center of the planet to the center of the sun.
Next, I create an acceleration vector along that line by creating its x and a y component:
$$\begin{align} Ax &= A\cos\theta & Ay &= A\sin\theta \end{align}$$
At the next iteration I use this acceleration vector and the time elapsed since the previous iteration to compute the planet's velocity and then its position. Then the whole thing repeats.
The main problem with this approach is that as soon as the planet reaches a distance close to zero from the sun, it gets a tremendous acceleration and at the next iteration it is simply too far from the sun and just keeps moving along a straight line, right out of the screen, which of course is not what I expect from gravity. Note that I still don't have collision detection so what I'd expect would be the planet to remain kind of still at the center of the sun.
My intuition is shouting that I should use some kind of integration for the acceleration so every acceleration that I miss between one iteration and the next would be taken into account and my planet would stop escaping gravity, so I recovered my math and physics books and tried to figure this out by myself, but no luck.
If I got this right the problem is that my acceleration is a function of distance, so I cannot integrate it in order to get the position for the planet, because that would require an acceleration as a function of time. Am I right? What's the right solution to this?