- Home /
Question by
_antifun_ · Sep 27, 2016 at 06:26 AM ·
physicsrigidbodygravitytrajectory
Calculating trajectory of Spaceship
Hello, I have a spaceship and a planet and I want to calculate its trajectory and draw it with LineRenderer. This is how I simulate gravity in FixedUpdate() in the Player Script.
void applyGravity() {
Vector3 attractionForce = Trajectory_Projection.calculateGravityAtPosition(rigidBody.position);
rigidBody.AddForce(attractionForce, ForceMode.VelocityChange);
}
// F = G * ((m1*m2)/r^2)
public static Vector3 calculateGravityAtPosition(Vector3 position) {
const float G = 9.81f * 50;
const float m = 1;
Vector3 attractionForce = Vector3.zero;
GameObject[] planets = GameObject.FindGameObjectsWithTag("Planet");
foreach (GameObject planet in planets) { //There's just one planet atm, don't worry that it will only take into consideration the last planet looped upon.
float r = Vector3.Distance(position, planet.transform.position);
float gravitationalForce = G * ((m * (planet.transform.localScale.x)) / Mathf.Pow(r, 2));
attractionForce = (planet.transform.position - position) * gravitationalForce;
}
return attractionForce;
}
And this is how I try to predict the trajectory:
void calculatePath() { //Called every frame
List<Vector3> positions = new List<Vector3>(); //Store predicted future positions.
List<Vector3> velocities = new List<Vector3>(); //Store predicted future velocities.
Vector3 lastPosition = playerRigidBody.position;
positions.Add(lastPosition);
Vector3 lastVelocity = playerRigidBody.velocity;
velocities.Add(lastVelocity);
for (int t = 0; t < 1000; t++) { //Calculate 1000 frames in advance.
lastPosition = positions[positions.Count - 1];
lastVelocity = velocities[velocities.Count - 1];
Vector3 newVelocity = (calculateGravityAtPosition(lastPosition) + lastVelocity);
Vector3 newPos = lastPosition + newVelocity;
positions.Add(newPos);
velocities.Add(newVelocity);
}
lineRenderer.SetVertexCount(1001);
lineRenderer.SetPositions(positions.ToArray());
}
This kind of works, but not really. Sometimes it resembles an orbit, but it's broken and the ship doesn't move like that. It also changes every frame even when I'm not applying any force to the ship, which shouldn't be the case: it should stay the same if no forces are being applied to the ship.
Anyone point me to a right direction, I'm not too strong on the math here.
Comment