Script: Callbacks and Timers
This page assumes that you know the basics about scripting.[br]
You probably reached a stage where you asked yourself "okay, I know how things work in theory - but how do I actually bring them alive?". You might want your object to interact with others or to do certain things on certain events.[br]
Callbacks
Callbacks are functions in your scripts that are called automatically when something special happens and which you can use to react to certain events. A common example is an object that explodes when it collides with the landscape, you would use the callback func Hit(int x_velocity, int y_velocity) for that. That function is called whenever your object hits the landscape (but not other objects!). To use a callback, you can simply write a function with the name of the callback into your script like that:[br]
func Hit(int x, int y)
{
Explode(100);
return;
}
[br]
Note that some callbacks also expect return values that define the reaction of your object. Take func RejectEntrance(object into_object) that you can use to prevent your object from being picked up, for example you might want your object to be non-collectable when it is on fire:[br]
func RejectCollect()
{
if (OnFire()) return true;
else return false;
}
Note that I omitted the parameter object into_object. The callback is still called. If you don't need certain parameters, you can leave them out.
[br]
If you want a callback that is called repeatedly every few frames, you can use the AddTimer(string name, int interval)
function to add a custom callback:[br]
// script of a mine
func Initialize() // called on object creation
{
AddTimer("Check", 30);
}
func Check() // our custom callback
{
// explode when a moving object is near
if (ObjectCount(Find_Distance(20), Find_OCF(OCF_HitSpeed1)) > 0)
Explode(30);
}
inheritance and _inherited()
When you read through some of the original scripts, you will find something weird like return _inherited(...) at the end of some callbacks. The function _inherited() is used to call the same function of the parent object when your object #includes another one. So for example when you write an extension to the Clonk, you might want that the original Clonk-script still receives the function call:[br]
func CatchBlow(int level) // CatchBlow is called when an object takes a hit
{
if (level > 10) Sound("Hurt*");
return _inherited(level, ...);
}
The three dots ... stand for all the other parameters that you did not assign a name. So if you have a named parameter you still have to write it manually into the _inherited-call. In the above example I omitted the object by parameter of CatchBlow.[br]
List of Callbacks
You can find a list of some of the callbacks here: C4Script Reference[br] Due to historic reasons there are (currently) not all existing callbacks listed. If you are looking for a certain callback that you are sure to exist, you can go into our IRC channel and ask ;)[br] [br]