Sub-Orbital Flight#

This introductory tutorial uses kRPC to send some Kerbals on a sub-orbital flight, and return them safely to Kerbin. It covers the following topics:

  • Controlling a rocket, by activating stages and setting the throttle

  • Using the autopilot to point the vessel in a direction

  • Using events to wait for things to happen in the game

  • Tracking the amount of resources in the vessel

  • Tracking flight data, such as altitude and vertical speed

  • Setting a part’s properties, such as a parachute’s deploy altitude

Note

For details on how to write scripts and connect to kRPC, see the Getting Started guide.

The tutorial flies the Kerbal 2, one of the game’s stock craft. Load it in the Vehicle Assembly Building and launch it to the pad before you run the script.

The tutorial includes source code for the main client languages kRPC supports. Download the whole program in your chosen language:

Python, C#, C++, C, Java, Lua, JavaScript

Preparing for Launch#

First we open a connection to the server, passing a name for the script. The name appears in the server window in the game. The C program also defines sleep_ms, which its polling loops pause with:

conn = krpc.connect(name="Sub-orbital flight")

Next we get an object representing the active vessel. We send instructions to the rocket through this object:

vessel = conn.space_center.active_vessel

Then we prepare the rocket for launch. This sets the throttle to half, and has the autopilot hold a pitch and heading of 90°, pointing straight up. It then waits a second for the settings to take effect:

vessel.auto_pilot.target_pitch_and_heading(90, 90)
vessel.auto_pilot.engaged = True
vessel.control.throttle = 0.5
time.sleep(1)

Lift-off!#

We launch by activating the first stage, which is the same as pressing the space bar. This lights the engine and releases the launch clamps:

print("Launch!")
vessel.control.activate_next_stage()

Pitching Over#

Once the rocket has cleared the launch pad, it starts to turn. We wait for an event that fires at an altitude of 500 m:

flight = vessel.flight()
event = conn.add_event(lambda: flight.mean_altitude > 500)
with event.condition:
    event.wait()

vessel.flight() returns a Flight object, which gives information about the rocket in flight, such as its altitude, direction and velocity.

The event is a server side function that compares the altitude with 500. The server checks it every physics tick, and the script sleeps until it fires.

The Python, C# and JavaScript clients compile the lambda into the function. The C++ and Java clients build it from expression objects: an embedded call to mean_altitude, a constant and a comparison. The C and Lua clients do not support events, so their scripts poll in a loop, with a short pause on each pass.

Now we tilt the rocket 20° from vertical, to a pitch of 70°, and hold a heading of 90°, due east. A target smoothing time of 10 seconds turns the rocket over gradually, rather than all at once:

print("Pitching over")
vessel.auto_pilot.target_smoothing_time = 10
vessel.auto_pilot.target_pitch_and_heading(70, 90)

The engine burns until the fuel tank is empty. We wait for an event that fires when less than 0.1 units of liquid fuel are left:

event = conn.add_event(lambda: vessel.resources.amount("LiquidFuel") < 0.1)
with event.condition:
    event.wait()

vessel.resources returns a Resources object, which gives the amounts of the resources in the rocket.

At flame out we cut the throttle, and the rocket coasts up to its apoapsis. The autopilot now points the rocket prograde, so it follows its arc:

print("Flame out")
vessel.control.throttle = 0
vessel.auto_pilot.reference_frame = vessel.surface_velocity_reference_frame
vessel.auto_pilot.target_direction = (0, 1, 0)

vessel.surface_velocity_reference_frame has its y-axis along the rocket’s velocity relative to the surface. So the direction (0, 1, 0) in this frame points prograde. The frame turns with the velocity, and the rocket turns with it.

Returning Safely to Kerbin#

We separate the capsule at apoapsis, where the rocket stops climbing. This waits for an event that fires when the vertical speed falls below zero:

body_flight = vessel.flight(vessel.orbit.body.reference_frame)
event = conn.add_event(lambda: body_flight.vertical_speed < 0)
with event.condition:
    event.wait()

This calls vessel.flight() again, now with a ReferenceFrame. We want the vertical speed relative to the surface of Kerbin, so the flight object has to give values in a frame fixed to Kerbin. vessel.orbit.body.reference_frame has its origin at the center of Kerbin, and rotates with the planet. See the Reference Frames guide for more.

Then we separate the capsule, and have the autopilot turn it retrograde. wait blocks until the capsule points there. We then disengage the autopilot, and the capsule’s drag keeps it pointing retrograde as it falls:

print("Apoapsis reached, separating")
vessel.control.activate_next_stage()
vessel.auto_pilot.target_direction = (0, -1, 0)
vessel.auto_pilot.wait()
vessel.auto_pilot.engaged = False

The Kerbals are now on a collision course with the surface. We wait until they fall to 2 km above the surface, then deploy the parachute. You can use time warp to skip ahead to just before this happens, and the script carries on working:

event = conn.add_event(lambda: flight.surface_altitude < 2000)
with event.condition:
    event.wait()

print("Deploying the parachute")
vessel.parts.parachutes[0].deploy_altitude = 550
vessel.control.activate_next_stage()

The parachute semi-deploys as soon as it is safe, which slows the capsule a little. It opens fully at its deploy altitude, 1000 m by default. We lower it to 550 m, so the capsule spends less time hanging under its parachute.

Finally, this prints the altitude of the capsule once a second, until it lands or splashes down:

situation = conn.space_center.VesselSituation
while vessel.situation not in (situation.landed, situation.splashed):
    print("Altitude = %.1f meters" % flight.surface_altitude)
    time.sleep(1)
print("Landed!")

Your Kerbals should now be safely back on Kerbin.