Events
Script can be called in a variety of ways. The most straightforward way is to have script run when an object emits an event. You can find events that are emitted by an object by looking under the Events group in the object's properties.
Whenever the object emits one of the events, script gets called. You can define the script for an event by clicking it in the Property Editor.
Let's take a look at the Trigger node to see how this works. A Trigger is a node that, when a node with the TriggerActivating attribute intersects its shape, will emit an 'onEnter' or 'onExit' event.
For instance, if a MeshEntity enters a particular Trigger, the following script would be called:
function Trigger:onEnter(obj)
-- Do something end
The 'obj' variable would represent the intersecting MeshEntity. You can use the 'self' variable from within the function to get the Trigger object itself. Now we can choose to do something interesting with the intersecting object. For instance, if we wanted to make it hop, we could add an impulse to its rigid body:
function Trigger:onEnter(obj)
-- add an impulse with a force added to the y-axis only
obj:getRigidBody():applyCentralImpulse(vector3(0,1,0))
end
Interaction Events
Some attributes that we attach to objects can add additional events to an object. For instance, we can attach the 'Interactable' attribute to a MeshEntity to add interaction events like onPress() and onHover() that fire when the user clicks the object or interacts with it via a laser. For instance, we can have an object fade out and get removed when we click it via the following code:
function MeshEntity:onPress(seg, normal, anchor_node)
self:fadeOutAndOrphan()
end
In the above function, 'seg' represents a segment that goes from the laser or mouse to the clicked point on the object. 'normal' is the surface normal of the point clicked and 'anchor_node' is the laser pointer itself (or nil if the mouse clicked it).
ScriptTracks
Another way script is called is at a particular point in time. We can do this by creating ScriptTracks on a Timeline. When the play head reaches a script event on the track, the script is called.
For instance, here's how we could turn the night-sky on at a specific point in time:
function ScriptTrack:onEvent()
SkySpace = getUniverse():getLibrary():findObjectByName("TerrainSpace").horizon.space
SkySpace.nightSky = true
end
Comments
0 comments
Please sign in to leave a comment.