I'm trying to calculate the xyz velocity vectors for a circular orbit given a set of position vectors, but I can't seem to get it right.
The formula for obtaining the velocity magnitude is the square root of gravitational constant multiplied by the mass of the primary divided by the distance from the primary to the object orbiting it. I'm using solar masses for mass, astronomical units for distance and years for time. To simplify things, the primary is our sun, which means that G * M is equal to 39.5. The position of the Sun is 0, 0, 0 and the vectors you see for Earth are in au and were obtained from the JPL Horizons tool.
Here's the code:
function getDistanceParams(p1, p2) {
const dx = p2.x - p1.x;
const dy = p2.y - p1.y;
const dz = p2.z - p1.z;
return { dx, dy, dz, dSquared: dx * dx + dy * dy + dz * dz };
}
function getCircularOrbit() {
const dParams = getDistanceParams(
{ x: 0, y: 0, z: 0 },
{
x: 0.9197324105567349,
y: -0.4147318273536994,
z: -1.750037390352759e-5
}
);
const vMag = Math.sqrt(39.5 / Math.sqrt(dParams.dSquared));
return {vx: dParams.dx * vMag, vy: dParams.dy * vMag, vz: dParams.dz * vMag};
}
getCircularOrbit();
/*
The above outputs this:
{ vx: 5.754832301294686,
vy: -2.59500707927136,
vz: -0.00010950110691846996 }
The actual velocity vectors:
vx: 2.4645428337894026,
vy: 5.7097644117945805,
vz: -3.3177815766459033e-4,
*/
Where am I going wrong???
Update: Code that works
In case anyone is curious, here's the code that ended up doing the job:
export function getDistanceParams(p1, p2) {
const dx = p2.x - p1.x;
const dy = p2.y - p1.y;
const dz = p2.z - p1.z;
return { dx, dy, dz, dSquared: dx * dx + dy * dy + dz * dz };
}
export function getIdealCircularOrbit(primary, secondary, g) {
const dParams = getDistanceParams(primary, secondary);
const d = Math.sqrt(dParams.dSquared);
const vMag = Math.sqrt(g * primary.m / d);
return {
x: secondary.x,
y: secondary.y,
z: secondary.z,
vx: primary.vx + -dParams.dy * vMag / d,
vy: primary.vy + dParams.dx * vMag / d,
vz: primary.vz + dParams.dz * vMag / d
};
}