Skip to content

Instantly share code, notes, and snippets.

@dewiniaid
Created May 19, 2016 05:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dewiniaid/1e57f68c903b38c03aedb552dabe4f95 to your computer and use it in GitHub Desktop.
Save dewiniaid/1e57f68c903b38c03aedb552dabe4f95 to your computer and use it in GitHub Desktop.
elements from state vector - Kerbalscript
REBOOT.
CLEARSCREEN.
@LAZYGLOBAL OFF.
// Direct port of https://github.com/RazerM/orbital/blob/0.7.0/orbital/utilities.py#L252
FUNCTION elements_from_state_vector {
PARAMETER r. // Position vector.
PARAMETER v. // Velocity vector.
PARAMETER mu. // Body mu.
LOCAL epsilon IS 1E-15.
LOCAL h IS VCRS(r, v). // Angular momentum.
PRINT "h=" + h.
// LOCAL n IS VCRS(V(0,0,1), h). // Node vector right-hand
LOCAL n IS VCRS(V(0,0,1), h). // Node vector.
PRINT "n=" + n.
LOCAL ecc IS ((v:mag^2 - mu/r:mag) * r - (r*v)*v):mag / mu. // Eccentricity.
//LOCAL ecc IS 1 / mu * ((norm(v) ** 2 - mu / norm(r)) * r - dot(r, v) * v)
PRINT "ecc="+ ecc.
LOCAL e IS (v:mag^2)/2 - (mu/r:mag). // Energy.
PRINT "e="+e.
// Not technically orbital parameters.
// Will fail if e=1, but it's unlikely to be exactly that anyways.
LOCAL a IS -mu/(2*e). // Semi-major axis.
PRINT "a="+a.
LOCAL p IS a*(1-ecc^2). // Parameter, semi-latus rectum
PRINT "p="+p.
//Inclination... if KSP was right-hand rule.
//LOCAL i IS arccos(h:z/h:mag). // Inclination. 0=polar, 90=equatorial.
//PRINT "i="+i. // 0 is polar, 90 equatorial
LOCAL i IS arccos(-h:y/h:mag). // Inclination. 0=polar, 90=equatorial.
PRINT "iy="+i. // KSP-normal(?)
}
elements_from_state_vector(-body:position, ship:velocity:orbit, body:mu).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment