Game Development Reference
In-Depth Information
In the function where a plane is shot down or a giant spider loses a leg, we can use the following:
function triggerPoint(theObject)
local points = theObject.value
Runtime:dispatchEvent({
name = "score",
points = points,
object = theObject
})
end
To tie the two together, we also need to set a listener, which is done using the addEventListener
function:
dispatchEvent function,
addEventListener function that listens to the score event.
Note A dispatchEvent requires that the event object be provided a name; this is used to identify it
when the listener filters the events and calls the appropriate handler function. You can pass any data in
the event object.
Alternatives to Events
As an alternative to using events, you can use callbacks . The shortcoming for callbacks, however, is
that instead of a radio station, it is more like a telephone conversation—a communication between
two parties. When you set a callback, it is set for one module alone. This is useful in scenarios such
as when we want to monitor something specific. For example, in a game, if connectivity is lost,
rather than broadcast that and have every function that relies on the network connectivity try to
manage the situation, we could simply have just one function that registers as the callback for that
event and handle the situation accordingly. Callbacks also provide a way to communicate between
the modules in the same application.
local theCallback = nil
local callback =
function(event)
print("callback called")
end
local mainLoop =
function()
for i=1, 20 do
if i==15 then
 
Search WWH ::




Custom Search