Question

I want to create FSM in Lua (using Luabind). Let's say I have GameObject, in lua file I do write this:

State1 = {}
State1["Start"] = function()
end
State1["Update"] = function()
    if (blah blah blah) then
        ChangeState(State2);
    end
end
State1["End"] = function()
end
... then states 2, 3 and etc...
gameObject.fsm = CreateFSMComponent(name, State1);

The question is - how to create the SAME object behavior with a DIFFERENT properties? Like.. if I would like to create 2 patrolling units with the same behavior but each of them would have the different start position. But in Lua - when I define external functions to describe these states within it - it doesn't work.

Was it helpful?

Solution

Are you asking how to create two objects in the same state (behaviour), but have different properties (like start position). If so, you can take either a functional approach, where you assume that the States just represent a series of functions operating on your objects (like PatrolUnits) like:

PatrolState = {}

PatrolState.Start = function(unit)
    if(SomeChecker(unit.startPos)) then
        DoSomething() -- like unit.curPos = unit.startPos, for example            
    end
end

PatrolState.Update = function(unit)
    if(IsNearSomething(unit.curPos)) then
        DoSomethingElse() -- like ChangeState(State2)
    end
end

, or an object oriented approach. In this case, you will have to make objects of type State1,2 ... and keep them around and you will be able to save properties like startPos in the state objects. For more info on how checkout this tutorial.

I prefer the former, since the States stay 'pure' and don't save unit's properties. But that's just a question of style.

-arun

edit: If your unit's position take special meaning based on what it's values are that logic can be embedded in the state machine code :

PatrolState.Update = function(unit)
    if(InsideDeathCircle(unit.position)) then
        ChangeState (KillUnitState)
    end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top