A to Z Scripting: Scripts that use input variables
Scripts that use input variables
A good way to avoid script duplication is to make use of input variables, allowing you to write a single longer script and pass it instructions from elsewhere, such as smaller scripts. Note that it won't be possible to call these scripts without input.
Input variables are defined in the round brackets next to the name of the script. They can then be used in the script itself:
Example: this script can be used to apply a variable amount of damage ("damage_amount") to any ai ("guard"):
void damage_guard(float damage_amount, ai guard) { float health_current = guard.getHealth(); float health_new = health_current – damage_amount; guard.setHealth(health_new); }
Other, shorter scripts can call the above script and give it input parameters to tell it which AI should be affected and how much damage:
void hurt_guard1_severe() { thread damage_guard($guard1, 50); //reduce guard1's health by 50 } void hurt_guard2_light() { thread damage_guard($guard2, 20); //reduce guard2's health by 20 }
(Note: the more correct way to damage an AI or the player is by applying a damageDef. These cause the entity on the receiving end to emit appropriate sounds, get blasted away etc.)
Example: multiple func_movers and buttons, movement in multiple directions
This is the main script that does the heavy lifting in applying the movements. It accepts input variables for a mover entity ("box"), movement duration ("move_time") and the movement vector ("move_vector").
void move_mover(entity box, float move_time, vector move_vector) { /* Main script that performs the movements. Gets called by and receives input parameters from move_forward() or move_backward(). Checks if the box is stationary. If the box is stationary, calculates new target position, sets time taken to move and then initiates movement. */ if(!box.isMoving()) //check if box has stopped moving { //define new target position based on current position + input move_vector vector target_position = box.getOrigin() + move_vector; box.time(move_time); //set time taken to move box.moveToPos(target_position); //initiate movement to the target position } }
These are the smaller scripts that pass instructions to the main script. Each one is called from a separate button in the map.
void move_forward_box1() //called by button1 in the map { thread move_mover($box1, 2, '50 0 0'); //box1, 2 seconds move_time, 50 units along the x axis } void move_backward_box1() //called by button2 in the map { thread move_mover($box1, 3, '-50 0 0'); } void move_forward_box2() //called by button3 in the map { thread move_mover($box2, 2, '50 0 0'); } void move_backward_box2() //called by button4 in the map { thread move_mover($box2, 3, '-50 0 0'); }
Next / previous article
- Next article: A to Z Scripting: Conditionals
- Previous article: A to Z Scripting: Practical exercise: subtle teleportation
- Table of contents: A to Z Scripting