I’m trying to create an accurate orbit. Here’s my code so far:

```
float XZVector2Magnitude(FVector v) {
return sqrt(pow(v.X, 2) + pow(v.Z, 2));
}
void ARotating_sphere::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
time += DeltaTime;
OldLocation = GetActorLocation();
FVector Distance = FVector((Star1Location.X - OldLocation.X), 0, (Star1Location.Z - OldLocation.Z));
// Force calculation
Force.X = ((Mass1 * Mass2) / pow(Distance.X, 2));
Force.Z = ((Mass1 * Mass2) / pow(Distance.Z, 2));
Velocity.X += ((Force.X) / Mass1);
Velocity.Z += ((Force.Z) / Mass1);
float Angle = (XZVector2Magnitude(Velocity) / XZVector2Magnitude(Distance));
NewLocation.X = OldLocation.X * cos(Angle) - OldLocation.Z * sin(Angle) + Velocity.X;
NewLocation.Z = OldLocation.X * sin(Angle) + OldLocation.Z * cos(Angle) + Velocity.Z;
SetActorLocation(NewLocation, false, 0, ETeleportType::None);
}
```

What I’m basically doing is updating the velocity by adding the acceleration (force/mass) and updating the position with this new velocity. The force is updated my multiplying the mass’s of the planet and the star and then dividing it by the distance. The idea is that when the planet is close to the star, the force is increased and the planet is slingshot around the star in order to create an accurate orbit.

The current problem is that I’m not sure what my initial values should be. Specifically the mass of the planet and star as well as the initial position. You see, if I set the planet’s position to be under the star then it actually slingshots around the planet but then just drifts off into space and doesn’t come back and if I set the position to be above the star then it just goes up. I’ve tried adding a gravity constant to the force calculation so that when the force decreases, the gravity will cause the planet to descend. I’ve also tried changing the force equation so it’s negative when the planet is above the star. The latter works a little bit better but I’m still running into the problem of consistency. Whenever the planet is going around the star, it’s traveling in a spiral where it keeps getting closer to the star and then begins to speed up. I just want the planet have a nice consistent orbit with the star that’s consistent and not slowly moving closer but I have no idea how I can do that.