Repository navigation
Connecting Vehicle Scripts, the Game Script and HTML UI
In Outerra a game usually has 3 parts:
- a game script that runs the game (rules, money, jobs)
- vehicles, and every vehicle model has its own script
- UI, the menus that the player sees, made with HTML
Often you need these 3 parts to talk to each other. For example the UI wants to show something that only the vehicle knows, or the game wants to change something on the vehicle, or the player clicks a button in the UI and the game needs to know it.
On this page you will see how to connect them. As an example we will make a fuel system: the vehicle uses fuel while driving, the player can see the fuel on the screen and can buy fuel at the gas station. The code is from Transport Minigame (a small game where the player delivers cargo with trucks), where this system already works. The examples are short parts of that code, so you can see how each connection works and use it the same way in your own scripts.
What is on this page:
- Section 1: how the 3 parts talk to each other
- Section 2: how the fuel system works, step by step
- Sections 3, 4 and 5: the code for each connection
- Section 6: common problems
Every part is a separate script. Here is what each one is, and what it does in the fuel system.
Every vehicle model has its own script (for example the Willys Jeep). It controls the engine, wheels, sounds, lights and the fuel tank.If there are 2 jeeps in the world, both use the same script, but each jeep is a separate vehicle instance with its own this object, so each one has its own fuel.
In the fuel system: each vehicle instance knows how big its tank is and how much fuel is in it. It uses fuel when the engine is running and the player presses the gas, and stops the engine when the tank is empty.
It's basically where the game starts and runs. It keeps the money, jobs, the player’s vehicles and the zones (areas on the map, like a gas station). It also spawns (creates) the vehicles. In our example it is one main file that loads a few other files (like the databases), but you can split it into more files as you like.
In the fuel system: the game script sits between the vehicle and the UI. Every frame it asks the vehicle how much fuel is left and shows the fuel on the screen. If the fuel is low, it warns the player. When the player buys fuel, it tells the vehicle the new amount.
The menus, like the gas station, the tow service and the phone. They don't keep any game data. They ask the game script for data and tell the game script when the player clicks something.
In the fuel system: when the gas station menu opens, the menu asks the game script for the fuel and the price. When the player clicks "Fill Tank", the menu tells the game script.
The UI never talks to the vehicle directly. Everything goes through the game script.
| What | From | To | Who starts it | When |
|---|---|---|---|---|
| fuel left in the tank, tank size | Vehicle | Game script | the game script asks | every frame |
| fuel, tank size, price | Game script | UI | the UI asks | when the menu opens |
| "player clicked Fill Tank" | UI | Game script | the UI tells | when the button is clicked |
| new fuel amount | Game script | Vehicle | the game script tells | after the player pays |
These scripts can't see each other's variables. So if a script wants to share something, it exposes a function: it makes the function available, so the other script can call it.
The scripts reach each other like this:
-
Game script → vehicle: the game script spawns the vehicles itself (with
ot::js::vehicle.create). When it spawns a vehicle, it gets back an object for that vehicle and keeps this object. With this object, throughscript_interface(), it can call the functions that this vehicle instance exposes. -
UI → game script: when the game script opens a menu, Outerra gives the menu a variable called
$module, which refers to the game script object. So the menu can call the functions that the game script exposes, like$module.get_fuel_price().
The code for each connection is in sections 3, 4 and 5.
The fuel is saved in 2 places:
-
In the vehicle instance (on its
thisobject). This is the real value. The vehicle lowers the fuel while driving. The vehicle instance also keeps the tank size (57 liters for the jeep). - In the game script. This is a copy, one for every vehicle the player has. The game script reads it from the vehicle and uses the copy for the screen, the warnings and the menus, so these parts don't have to ask the vehicle themselves.
- On every physics step, the vehicle lowers its fuel if the engine is running and the player presses the gas. At idle (no gas) it doesn't use fuel.
- Every frame, the game script reads the fuel from the vehicle and updates its copy.
- The game script shows the fuel on top of the screen, like "Fuel: 41 / 57 L". The game script draws this text itself with the canvas API, it is not an HTML menu. At 40% or less the text becomes orange. At 10% or less the text becomes red and blinks between the fuel and "LOW GASOLINE!".
- When the fuel goes under 10%, and again when it is 0, the game script sends a message to the player's phone. Each message comes only one time in a game session, for tutorial purposes. If the player refuels and the fuel goes low again, there is no new message.
- The player drives into a gas station zone. The game script sees that the player is in the zone and shows a text on the screen that tells the player to press the interaction key.
- The player presses the interaction key. The game script opens the gas station menu.
- The menu asks the game script for the fuel and the price, and shows them.
- The player clicks Fill Tank. The menu tells the game script.
- The game script checks if the player is at a gas station and has enough money. If yes, it takes the money, sets its copy to a full tank, and tells the vehicle the new fuel amount, so the fuel needle on the dashboard goes up. If the player doesn’t have enough money, the game script shows “Not enough funds for fuel!” on the screen and nothing changes.
Now let’s look at the code behind the fuel system.
Outerra calls 2 setup functions in every vehicle script by itself:
-
init_chassis()runs only one time for a vehicle model, when the model is loaded (and again if the model is reloaded). What it sets up is shared by all vehicles of this model, like wheels, sounds, lights and controls. -
init_vehicle()runs again for every vehicle that is spawned. The code is the same for all jeeps, so they all start with the same values (for example 57 liters of fuel). But every vehicle instance has its own values, so later they can be different: one jeep can have 10 liters left while another one is still full.
Every vehicle instance needs its own fuel tank, so the fuel code goes into init_vehicle().
Inside init_vehicle(), this refers to the current vehicle instance being initialized. If you put a function on this, the game script can call it on that vehicle:
function init_vehicle() {
// ...
// Tank size and fuel in the tank, in liters. The vehicle starts with a full tank.
this.fuel_capacity = 57.0;
this.remaining_fuel = this.fuel_capacity;
this.last_fuel_pos = null; // last position, used to burn more fuel when going uphill
// The game script calls this function to read the tank size
this.get_fuel_capacity = function () {
return this.fuel_capacity;
};
// The game script calls this function to read the fuel
this.get_remaining_fuel = function () {
return this.remaining_fuel;
};
// The game script calls this function to change the fuel (for example when refueling)
this.set_remaining_fuel = function (amount) {
this.remaining_fuel = amount;
};
}The jeep script also uses this.remaining_fuel in 2 other places:
-
simulation_step(dt)runs on every physics step. When the engine is running and the player presses the gas, it lowers the fuel. At idle it doesn't use fuel. More throttle, higher RPM and going uphill use more fuel. When the fuel is 0, the engine stops and the player sees "Out of fuel!". The jeep uses this formula:// In simulation_step(dt) if (this.engine_state == EngineState.esStarted && this.remaining_fuel > 0) { let throttle = Math.abs(this.engine_load || 0); if (throttle > 0.01) { // no gas = no fuel use // ... calculate weight_multiplier, slope_multiplier and rpm_ratio ... let engine_load_total = throttle * weight_multiplier * slope_multiplier * rpm_ratio; let fuel_drain = engine_load_total * jeep_base_rate * dt; // jeep_base_rate = 0.04 this.remaining_fuel -= fuel_drain; if (this.remaining_fuel < 0) this.remaining_fuel = 0; } } // Stop the engine when the tank is empty if (this.remaining_fuel <= 0 && this.engine_state == EngineState.esStarted) { this.engine_state = EngineState.esStalling; this.fade("Out of fuel!"); }
-
throttle: how much the player presses the gas, from 0 to 1 -
rpm_ratio: engine RPM divided by the max RPM (at least 0.1) -
weight_multiplier:1 + (mass / 1100) * 0.15. It is there for heavier vehicles: more mass uses more fuel. The jeep's mass is always 1100, so for the jeep it is always 1.15 -
slope_multiplier: 1 on a flat road, up to 3 when going uphill, down to 0.1 when going downhill -
dt: the time since the last physics step, in seconds
-
-
update_frame(dt)runs every frame and moves the fuel needle on the dashboard, usingthis.remaining_fuel / this.fuel_capacity.
ot::js::vehicle.create spawns a new vehicle in the world and gives back an object for that vehicle. The game script keeps this object and uses it later to control the vehicle (get in, move it, get its position and so on).
script_interface() gives back the script object of that vehicle instance, the same this that init_vehicle() set up. So to call a function like get_remaining_fuel(), first call script_interface() on the vehicle object:
// Spawn a vehicle and keep its object
let vehicle = engine_module.$query_interface('ot::js::vehicle.create', path, pos, rot);
// Later: call the functions that init_vehicle() put on this vehicle instance
let script_api = vehicle.script_interface();
if (script_api && typeof script_api.get_remaining_fuel === 'function') {
// Save the fuel in the game script's copy
vehicle_fuel_levels[active_vehicle_id] = script_api.get_remaining_fuel();
}Note: what is
engine_module? It refers to the game script object. Insideon_initialize(),thisrefers to the game script object, but in other functions likenew_game()orvisual_update(),thisis something else. So at the start ofon_initialize()the game script saves itself in a variable:engine_module = this;. After that, every function can useengine_moduleto reach the game script. You will see it in many examples.
In Transport Minigame all spawned vehicles are kept in spawned_vehicles, and the vehicle that the player drives is current_vehicle.
The typeof ... === 'function' check is there because not every vehicle script puts the same functions on its instance. A vehicle from another mod maybe doesn't have get_remaining_fuel. Without this check the script gives an error.
Outerra calls on_initialize() one time when the game starts. Here this refers to the game script object.If you put a function on this here, every HTML menu can call it.
function on_initialize() {
// Save the game script as engine_module
engine_module = this;
// Only gives back a value
this.get_fuel_price = function () {
return fuel_price_per_liter;
};
// Gives the fuel of the vehicle the player drives
this.get_vehicle_fuel = function () {
let script_api = current_vehicle.script_interface();
return {
current: vehicle_fuel_levels[active_vehicle_id],
max: script_api.get_fuel_capacity()
};
};
// Changes something and says if it worked
this.refuel_vehicle = function () {
// ... checks if the player is at a gas station and has enough money ...
return true; // or false
};
return true;
}Some simple rules we use for these functions:
- Functions that start with
get_,is_orcheck_only give back information, they don't change anything. - Functions that do something (buy, refuel, accept a job) give back a result, so the menu knows if it worked. This is
true/falseor a short text like"SUCCESS","INSUFFICIENT_FUNDS"or"NO_PARKING".
The game script opens a menu with open_window:
let ui_params = `?width=${screen_size.x}&height=${screen_size.y}&transparent=true&frame=false&alpha=true`;
engine_module.open_window("www/gas_station.html" + ui_params);The part after ? sets the size and the look of the window. You can also add your own values there and the menu can read them when it opens. The tow service menu gets its prices like this:
engine_module.open_window("www/tow_service.html" + ui_params +
`&base_cost=${base_cost}&fuel_cost=${fuel_cost}&out_of_fuel=${is_out_of_fuel}`);Use these values for things that are calculated one time when the menu opens. If something can change while the menu is open (like the fuel when refueling), call a game script function instead.
In the HTML, $module refers to the game script object, the same object as this in on_initialize(). Write var $module; at the top of your script, Outerra fills it when it opens the menu. After that you can call every function that the game script exposes, like $module.function_name():
<script>
var $module;
window.onload = function () {
refreshUI();
};
function refreshUI() {
// If you open the page outside the game (for example in a browser), $module is empty
if (typeof $module === 'undefined') return;
let fuel = $module.get_vehicle_fuel(); // gives { current, max }
let price = $module.get_fuel_price();
document.getElementById("fuel-text").innerText =
`${Math.floor(fuel.current)} / ${fuel.max} L`;
}
function requestRefuel() {
if ($module.refuel_vehicle()) refreshUI();
}
</script>You get the answer right away, you don't need to wait.
Values that the game script adds to the URL always come as text, even if they look like a number or true/false. So you need to change them first:
const urlParams = new URLSearchParams(window.location.search);
const baseCost = parseInt(urlParams.get('base_cost')); // text -> number
const isOutOfFuel = urlParams.get('out_of_fuel') === 'true'; // text -> true/false
const galId = urlParams.get('gal_id'); // can be the text "null"This is important when you send the value back. For example confirm_tow_service checks if out_of_fuel is true. The text "true" is not the same, so if you send the text, the player doesn't get the emergency fuel.
Before you close a menu, tell the game script that the menu is closed:
function closeUI() {
$module.close_active_menu();
window.close();
}
// Also close with ESC
document.addEventListener("keydown", function (e) {
if (e.keyCode === 27) closeUI();
});If you only call window.close(), the game script thinks the menu is still open. Then the zone prompt doesn't come back and the interaction key doesn't work until the player leaves the zone.
| Problem | Reason |
|---|---|
| After closing a menu, the zone prompt doesn't come back |
close_active_menu() is not called before window.close()
|
| A button does nothing | A value from the URL is sent back as text ("true"), not as true
|
| A new vehicle always shows a full tank | The vehicle script doesn't put get_remaining_fuel / set_remaining_fuel / get_fuel_capacity on this in init_vehicle()
|
Test