What’s the best way to handle player states?

So say I have multiple states in a shooter game to represent different actions the player can do nonconcurrently, like shooting and sprinting. With a system like this I want the player to be able to hold M1 to enter the shooting state, lowering their movement speed slightly and firing the gun’s raycast function off cooldown, but then also be able to press the sprint button, overwriting the shooting state with the sprinting state, which stop the gun from firing and increases WalkSpeed. How would I make it so that keeping M1 held will cause the player to resume shooting after they release sprint?

u might be looking for something called a finite state machine

you will have to create your own state manager… may seem daunting at first, but i’ll save you the core details. i’ll give you some examples from my own state manager.

first you’ll start off by creating your own module:

local stateManager = {}
stateManager.defaults = require(script.Defaults)
stateManager.__index = stateManager

return stateManager

and under the defaults module, describe what states you should have on spawn. it’s actually pretty simple to remove and add your own values.

return {
	--// interactive states
	isDead = false,
	isInvulnerable = false,
	isCrouching = false,
	isProne = false,
	isIncapped = false,
	toolsUsable = false,
	isRagdoll = false,
	isHoldingTool = false,
	heldTool = nil,
	--// movement states
	isWalking = false,
	isRunning = false,
	isJumping = false,
	isFalling = false,
	isSitting = false,
	isClimbing = false,
	isSwimming = false,
	hasLanded = false,
	--// character info
	health = 100,
	maxHealth = 100,
	walkspeed = 13,
	jumpPower = 50,
	lastPosition = Vector3.zero,
	transparencyModifier = 1,
	fallData = {
		minDistance = 100,
		maxDistance = 200
	},
	deathCause = "",
}

then add your main state register:

--[[
registers a state for a character

@contexts server*
]]
function stateManager.register(character)
	local self = setmetatable({}, stateManager)

	--// client information
	self.currentChar = character
	self.currentPlayer = players:GetPlayerFromCharacter(character)
	self.currentHum = character:FindFirstChildWhichIsA("Humanoid")

	--// state register
	self.state = {}
	for state, value in stateManager.defaults do
		self.state[state] = value
	end

	--// state changes
	self.stateChangedBind = Instance.new("BindableEvent")
	self.stateChanged = self.stateChangedBind.Event

	--// connections
	self.connections = {}

	--// tracking
	self:_startTracking()

	return self
end

then add some basic tracking functions.

--[[
update movement states

@contexts internal*
]]
function stateManager:_updateMovement(humState)
	--// set all based on current state
	self:Set("isJumping", humState == Enum.HumanoidStateType.Jumping)
	self:Set("isFalling", humState == Enum.HumanoidStateType.Freefall)
	self:Set("isSitting", humState == Enum.HumanoidStateType.Seated)
	self:Set("isClimbing", humState == Enum.HumanoidStateType.Climbing)
	self:Set("isSwimming", humState == Enum.HumanoidStateType.Swimming)

	--// fall detection
	local root = self.currentChar:WaitForChild("HumanoidRootPart")

	local currentHealth = self:Get("health")

	local rootVelocity = root.AssemblyLinearVelocity.Y * -1
	local fallData = self:Get("fallData")

	if rootVelocity >= fallData.maxDistance then	
		self:ApplyHealthEffect(currentHealth, "damage")
		self:Set("deathCause", "fall")
	elseif rootVelocity >= fallData.minDistance then
		self:ApplyHealthEffect(rootVelocity/4, "damage")
		self:Set("deathCause", "fall")
	end
end

--[[
start tracking basic character states

@contexts internal*
]]
function stateManager:_startTracking()
	table.insert(self.connections, self.currentHum.StateChanged:Connect(function(oldState, newState)
		self:_updateMovement(newState)
	end))

	table.insert(self.connections, self.currentHum.HealthChanged:Connect(function(health)	
		local incapThreshold = self:Get("maxHealth")/6
		local isDead = health <= 0

		self:Set("health", health)
		self:Set("isDead", isDead)
		self:Set("isIncapped", health <= incapThreshold and not isDead)
	end))

	table.insert(self.connections, self.currentHum:GetPropertyChangedSignal("MoveDirection"):Connect(function()
		local moveVector = self.currentHum.MoveDirection
		local currentState = self.currentHum:GetState()
		local walkSpeed = self:Get("walkspeed")

		if moveVector.Magnitude > 0 then
			self:Set("isWalking", walkSpeed <= 19)
			self:Set("isRunning", walkSpeed > 19)
		elseif moveVector.Magnitude == 0 then
			self:Set("isWalking", false)
			self:Set("isRunning", false)
		end
	end))

	table.insert(self.connections, self.currentChar.ChildAdded:Connect(function(addedInstance)
		if addedInstance:IsA("Tool") then
			self:Set("isHoldingTool", true)
			self:Set("heldTool", addedInstance)
		end
	end))

	table.insert(self.connections, self.currentChar.ChildRemoved:Connect(function(removedInst)
		local lastTool = self:Get("heldTool")

		if removedInst == lastTool and removedInst:IsA("Tool") then
			self:Set("isHoldingTool", false)
			self:Set("heldTool", nil)
		end
	end))

	self:Set("health", self.currentHum.Health)
	self:Set("maxHealth", self.currentHum.MaxHealth)
	if self.currentChar.PrimaryPart then
		self:Set("lastPosition", self.currentChar.PrimaryPart.Position)

		table.insert(self.connections, self.currentChar.PrimaryPart:GetPropertyChangedSignal("Position"):Connect(function()
			self:Set("lastPosition", self.currentChar.PrimaryPart.Position)
		end))
	end
end

add some set & get functions:

--[[
set the value of a specified state if it exists

@contexts: server*
@params state: string, the name of the state
@params value the value to set the state to
]]
function stateManager:Set(state, value)
	local oldValue = self.state[state]
	self.state[state] = value

	if oldValue ~= value then -- only if the value actually changed
		self.stateChangedBind:Fire(state, value, oldValue)
		remotes.ClientStateChanged.Event:FireClient(
			self.currentPlayer, 
			{
				State = state, 
				Value = value, 
				oldValue = oldValue, 
				FuncName = "clientStateChange"
			}
		) -- this is to notify the client if a state changed
	end
end

--[[
returns the value of a specified state if it exists

@contexts server, client
]]
function stateManager:Get(value)
	return self.state[value]
end

then the most IMPORTANT part of this all… add a subscription callback

--[[
subscribe a callback function to be called when a state changes

@contexts server, client
@params key: string, the name of the state
@params callback: function, the function to fire when the state changes
]]
function stateManager:Subscribe(key:string, callback:(newVal:any, oldVal:any) -> ()):RBXScriptSignal
	local connection = self.stateChanged:Connect(function(changedKey, newVal, oldVal)
		if changedKey == key then
			local success, err = pcall(callback, newVal, oldVal)
			if not success then
				error("Subscription callback to key "..key.." failed. Error: "..err)
			end
		end
	end)

	if not self.connections[key] then
		self.connections[key] = {}
	end
	table.insert(self.connections[key], connection)

	return connection
end

--[[
subscribe a callback function to be called when any state changes

@contexts server, client
@params callback: function, the function to fire when the state changes
]]
function stateManager:SubscribeToAll(callback:(key:string, newVal:any, oldVal:any) -> ())
	return self.stateChanged:Connect(callback)
end

then, under a server script, initialize and create the character state.

player.CharacterAdded:Connect(function(character)
		local characterState = StateManager.register(character) -- < right here
		local humanoid:Humanoid = character:WaitForChild("Humanoid")
		local animator = humanoid:FindFirstChildWhichIsA("Animator")
		humanoid.WalkSpeed = characterState:Get("walkspeed")
		humanoid.BreakJointsOnDeath = false
-- rest of the logic is missing, you get the gist though

subscribing to a key is simple, just do

characterState:Subscribe("lastPosition", function(newVal, oldVal)
			print(newVal)
		end)

and that should be all… it’s a bit long but this is what you sadly have to do when tracking states

1 Like