Scripting Tasks
This page lists examples for solutions of often recurring scripting tasks. If you know a better or other way of doing something or have any suggestions or ideas, feel free to edit / add to this page!
drain energy while equipment is being used (simulate energy usage)
using a Timer and it's callback function (modified example taken from Ore Processor):
Overview
This solution uses a Timer and it's callback function. When the equipment is activated, the timer is being started. The timer is configured to fire every 0.5 seconds. Every time it fires, the callback function this.$drainEnergy is being called, which reduces the ships' energy by a certain value (here: by 6.4). Note: for simplicity, the code shown here is reduced to only those parts that simulate the energy usage. Have a look at the original source code of the Ore Processor OXP for more info (e.g. howto play a sound while energy is drained).
1. Timer setup
The timer this.$energyDrainTimer that periodically calls the energy reducing method has to be configured. Here this is done in the method this.startUp (which is part of a world script):
this.startUp = function () { this.$energyDrainTimer = new Timer(this, this.$drainEnergy, 5, 0.5); this.$energyDrainTimer.stop(); }
2. prepare energy reducing function
Together with the timer, this method simulates the energy draining by reducing the ships' energy every time that it is called. If the ships' energy drops to 64, the energy drain will stop (for safety):
this.$drainEnergy = function () { if (player.ship.energy > 64) { player.ship.energy -= 6.4; // do something with the used energy here } else { player.consoleMessage("Energy failure!!"); this.$energyDrainTimer.stop(); } }
3. start/stop the timer when equipment is activated/deactivated
In the actual OreProcessor.oxp, the function energy draining function is called when a splinter is scooped. To make things simpler, that has been changed for this example. Now there exist functions this.$activateEnergyDrain and this.$deactivateEnergyDrain which simply start or stop the timer:
this.$activateEnergyDrain = function () { this.$energyDrainTimer.start(); }
this.$deactivateEnergyDrain = function () { this.$energyDrainTimer.stop(); }
Links
- script tool: Exception traceback (cag, 2020)
- Using JavaScript's try ... catch statement, a primitive form of call stack traceback is possible.