Мой текущий код ↓ < /p>
Код: Выделить всё
export function findSecondFocus(i) {
let parentIndex = bodies[i].parentIndex;
let parent = bodies[parentIndex];
const relativeSpatiumVector = [
bodies[i].position[0] - parent.position[0],
bodies[i].position[1] - parent.position[1],
];
//calculate the relative position vector of the body relative to what its orbiting
const relativeVelocityVector = [
bodies[i].velocity[0] - parent.velocity[0],
bodies[i].velocity[1] - parent.velocity[1],
];
//calcualte the relative velocity
const r = Math.hypot(relativeSpatiumVector[0], relativeSpatiumVector[1]);
// r represents the distance between the body and what it is orbiting
// uses math.hypot to form a right angle to triangle to use pythagoras theorem to calculate the scalar distance
const velocityScalar = Math.hypot(
relativeVelocityVector[0],
relativeVelocityVector[1]
);
const mu_sim = gravity * parent.mass;
const specificOrbitalEnergy = velocityScalar ** 2 / 2 - mu_sim / r;
//calcualtes specific orbital energy which is the sum of their potetial and kinetic energies.
//it is given by ε=v^2/2 -μ/r where μ=GM
const a = -mu_sim / (2 * specificOrbitalEnergy);
//calcualte the semi-major axis by rearranging ε=-μ/(2a)
// The eccentricity vector formula is: e = (v × h)/μ - r/|r|
const rvDot = relativeSpatiumVector[0] * relativeVelocityVector[0] +
relativeSpatiumVector[1] * relativeVelocityVector[1];
const rUnit = [
relativeSpatiumVector[0] / r,
relativeSpatiumVector[1] / r
];
const eccentricityVector = [
((velocityScalar**2 - mu_sim / r) * rUnit[0] - rvDot * relativeVelocityVector[0]) / mu_sim,
((velocityScalar**2 - mu_sim / r) * rUnit[1] - rvDot * relativeVelocityVector[1]) / mu_sim,
];
const eccentricityScalar = Math.hypot(
eccentricityVector[0],
eccentricityVector[1]
);
//calculate the eccentricity of the orbit
const eccentricityUnitVector = [
eccentricityVector[0] / eccentricityScalar,
eccentricityVector[1] / eccentricityScalar,
];
//convert ecentricity to a unit vector by dividing by its magnituted so that it has a length of 1
const distanceFromCentre = a * eccentricityScalar; // c = ae
// First focus is at parent position
// Center is OPPOSITE to eccentricity direction from first focus
const ellipseCenter = [
parent.position[0] - distanceFromCentre * eccentricityUnitVector[0],
parent.position[1] - distanceFromCentre * eccentricityUnitVector[1],
];
// Second focus is equal distance on OTHER side of center
const secondFocus = [
ellipseCenter[0] - distanceFromCentre * eccentricityUnitVector[0],
ellipseCenter[1] - distanceFromCentre * eccentricityUnitVector[1],
];
//finally calculate the position of the second focus point by offsetting the position of the first focus (parent planet) by 2 times the distance from the centre of the ellipse
console.log(secondFocus);
console.log("Eccentricity:", eccentricityScalar);
console.log("Semi-major axis:", a);
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... it-ellipse