Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- StateManager.lua
- local Knit = require(game:GetService("ReplicatedStorage").Packages.Knit)
- local StateManager = Knit.CreateService {
- Name = "StateManager",
- }
- local Players = game:GetService("Players")
- local StateClass = require(script.StateClass)
- local LastChange = nil
- local AlreadyCounting = false
- local StateMachines = {
- HumanoidStateMachine = {},
- CombatStateMachine = {}
- }
- local IDLE_REVERT_TIME = 5
- local ITERATION_INTERVAL = 1
- local function ConfigureStates(Character)
- local Humanoid = Character:WaitForChild("Humanoid")
- local HumanoidStateMachine = StateMachines.HumanoidStateMachine
- Humanoid.StateChanged:Connect(function(_, NewState)
- if NewState ~= Enum.HumanoidStateType.Running then
- HumanoidStateMachine:ChangeState(NewState.Name)
- end
- LastChange = os.clock()
- if AlreadyCounting then return end
- AlreadyCounting = true
- while true do
- task.wait(ITERATION_INTERVAL)
- local DeltaTime = os.clock() - LastChange
- if DeltaTime >= IDLE_REVERT_TIME then
- break
- end
- end
- HumanoidStateMachine:ChangeState("Idle")
- AlreadyCounting = false
- end)
- HumanoidStateMachine:ChangeState("Idle")
- end
- function StateManager.KnitInit()
- for StateMachine,_ in StateMachines do
- StateMachines[StateMachine] = StateClass.new(StateMachine)
- end
- Players.PlayerAdded:Connect(function(Player)
- if Player.Character then ConfigureStates(Player.Character) end
- Player.CharacterAdded:Connect(ConfigureStates)
- end)
- end
- return StateManager
- StateClass.lua
- local StateClass = {}
- StateClass.__index = StateClass
- function StateClass.new(StateMachine)
- local self = setmetatable({}, StateClass)
- self.Name = StateMachine.."StateMachine"
- self.States = {}
- for _,State in ipairs(script[StateMachine]:GetChildren()) do
- self.States[State.Name] = require(State)
- end
- self.State = self.States["None"]
- return self
- end
- function StateClass:ChangeState(State)
- local ValidState = false
- for StateName, Other in self.States do
- if StateName == State then
- ValidState = true
- break
- end
- end
- if not ValidState then
- error("Attempted to change state to invalid state enum: "..tostring(State))
- end
- local OldState = self.State
- local NewState = self.States[State]
- if OldState.Exit then OldState.Exit() end
- if NewState.Enter then NewState.Enter() end
- self.State = NewState
- print("State Change:",self.State.Name)
- end
- function StateClass:FetchState(State)
- return self.State
- end
- return StateClass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement