kOS Hovercraft - code in comments!

I made a very reliable hovercraft using kOS which can whip you around Kerbin at 60-100m/s, 3 meters from the ground, without hitting any terrain. I figure it's great on Kerbin and would be ever more practical on Mun/Minmus etc.

This code will work with ANY ship with a decent TWR and attitude control, on any body, as long as the control module faces forward and thrust vectoring is turned off on the engines. Copy the code below:

//must have control module facing forward (if facing up, must change some vectors) //must turn off liquid fuel thrust vectoring. //need to have reaction wheels or control surfaces.

set alt1 to alt:radar. //radar altitude of ship set vertspeed to 0. //vertical speed relative to terrain, per tick (not m/s) set hoverlevel to 3. //height above terrain at 0-20 m/s

function setThrottle { //function to set throttle declare parameter x. set ship:control:pilotmainthrottle to x. } function updateAlt{ //update radar altitude. set vertSpeed to (alt:radar - alt1). set alt1 to alt:radar. } function setHoverThrust { //recalculate thrust needed to exactly oppose gravity. set hoverThrust to ship:mass((body:massconstant:g)/((body:radius+ship:altitude)2))/maxthrust. } //must be run every tick to account for fuel redistribution

setHoverThrust(). setThrottle(hoverThrust). //initialize throttle until (ship:control:pilotmainthrottle = 0) { //until player presses "x" to terminate program

set targetThrust to hoverThrust. //initalize modifier for thrust set targetThrust to targetThrust + ((-vertspeed * 10)ship:mass10)/maxthrust. //increase or decrease throttle to oppose changes in vertical speed to keep ship same level above ground

if ship:groundspeed > 20 { //if speed goes above 20 m/s, increase ground clearance by 1 meter per 10 m/s set hoverlevel to (ship:groundspeed/10)+1.} //can't save you from smashing to cliffs at 100m/s else { set hoverlevel to 3.} //but better than nothing.

set offset to hoverlevel-alt1. //another modifier to increase or decrease throttle based on distance from the ground if offset > 3 {set offset to 3.} //avoiding large changes in speed or acceleration if offset < -3 {set offset to -3.} //for example, if you hover off a cliff, you will come down slowly. set targetThrust to targetThrust + offset/5.

set targetThrust to targetThrust * (1/sin(vectorangle(up:vector,ship:facing:vector))). //finally, modify thrust based on angle of ship (and engines) relative to "up".

if targetThrust < 0.01 {set targetThrust to 0.01.} //avoid tripping shutdown condition setThrottle(targetThrust).

wait 0.1. //wait .1 seconds, update values updateAlt(). setHoverThrust(). } setThrottle(hoverThrust*.5). //on engine shutdown, throttle down over .5 seconds. wait .5. setThrottle(0).

/r/KerbalSpaceProgram Thread Link - gfycat.com