Game Development Reference
In-Depth Information
How to do it...
As with the previous examples, we begin by creating a new class that extends the
ScriptObject
interface. We can call it
AIScriptControl
.
1. It needs to have an
AIControl
field called
aiControl
and a
Class<AIState>
field called
targetState
.
2. It might also have a
Spatial
called
target
.
3. Finally, we add a Boolean called
enabled
.
4. In its
trigger
method, we should call
onTrigger
if
enabled
is
true
.
5. In the
onTrigger
method, we apply
targetState
to
aiControl
:
aiControl.setState(targetState);
6. If
target
is not null, we call
aiControl.setTarget(target)
.
7. The
StateMachine
for the
AIControl
we created was a closed system and it
didn't need any external input to change the states. Now, we need to be able to trig-
ger it externally so let's add a setter method in the
AIControl
. Create a new
method called
setState
, which takes a
Class<AIState>
called
state
as
an input parameter.
8. Inside, we check whether
spatial
has the supplied state, and enable it if pos-
sible:
if(spatial.getControl(state) != null){
spatial.getControl(state).setEnabled(true);
}