A attempt at making a finite state machine

Hey everyone, I’ve been trying to make some guard AI for my game and I have been messing around with Finite State Machines (FSM) to try and organize my script better and make the AI modular. This is currently the script for the AI:

https://gist.github.com/sharaalt/06a7150150a4d95651f1283c9c8bdb6e (I ran into some trouble trying to past the code since it was to big :melting_face: )

And these are the state definitions:

--[=[
	@class GuardStates
]=]

local GuardStates = {}

local Promise = require(game.ServerScriptService.Dependencies.promise)

function GuardStates.Idle(guard)
	return {
		Name = "Idle",
		OnEnter = function()
			print("Starting Idle")
			guard._idleAnim:Play()
			guard._walkAnim:Stop()
		end,
		OnExecute = function()
			print("Idling")
			task.wait(1)
		end,
		OnExit = function()
			print("Done idling")
		end,
	}
end

function GuardStates.Patrol(guard)
	return {
		Name = "Patrol",
		OnEnter = function()
			print("Starting patrol")
		end,
		OnExecute = function()
			guard:MoveGuard(guard._waypoints)
		end,
		OnExit = function()
			print("Done patrolling.")
		end,
	}
end

function GuardStates.Chase(guard)
	return {
		Name = "Chase",
		OnEnter = function()
			print("Starting patrol")
		end,
		OnExecute = function()
			local distance = (
				guard._guard:WaitForChild("HumanoidRootPart").Position
				- guard._currentPlayer.Character.HumanoidRootPart.Position
			).Magnitude

			guard
				:RequestNewPath(guard._currentPlayer.Character.HumanoidRootPart.Position)
				:andThen(function(val)
					if distance < 5.5 then
						guard.PlayerLost:Fire()
					end
					guard:MoveGuard(val)
				end)
				:catch(warn)
				:await()
		end,
		OnExit = function()
			print("Done chasing.")
		end,
	}
end

return GuardStates

I would like some feedback on how I could better both the states and the core guard AI. When the AI does chase the player it doesn’t feel fluid it just goes to the players last know location not actively going to the player is there anyway to fix that :thinking:

Currently this is how the bots function

There should probably be a state where they run directly to the player when they’re in direct line of sight?

1 Like

Yeah, I was thinking about implementing something like that thanks for the feedback though!