Need Help Understanding and Implementing a State Machine for a Combat System

Hello! Recently, someone suggested that I should use a state machine for my combat system. However, I don’t really understand how a state machine works or what it actually represents in practice. I’m also not sure how to design or implement one for a combat system.

Could someone please explain the basic concept of a state machine, why it is useful in game combat systems, and how I can start creating one step by step? Examples or simple explanations would be greatly appreciated.

Thank you in advance for your help!

State machines basically tell the npc how it should and when to behave. It’s much better than handling multiple different possible edge cases.

A basic example would be

Listen for “Idle” state → If not state “Attacking” then → Free roam
Listen for “Attack” state → If state “Idle” then → Find and attack the nearest player

Well, then for my combat system I can set a string attribute on the character called State.

When the player is attacking, it will be set to “Attacking”.

I can also define a list of transitions that determine which states the player can switch between, for example:

Idle → Attacking → Stunned

Attacking → Idle → Stunned

Did I get this right?

Yes that works, but what I did was create my own state manager module where it makes it easy to change states and detect changes. I would show but I’m currently away from my pc

Like this?

local AllowedTransitions = {
	Idle = {
		Attacking = true,
		Blocking = true,
	},
	Attacking = {
		Idle = true,
		Stunned = true,
	},
	Blocking = {
		Idle = true,
		Stunned = true,
	},
	Stunned = {
		Idle = true,
	}
}


local function SetState(player: Player, newState: string)
	local currentState = player:GetAttribute("State") or States.Idle

	if not AllowedTransitions[currentState] then return false end
	if not AllowedTransitions[currentState][newState] then
		warn(`Invalid transition: {currentState} → {newState}`)
		return false
	end

	player:SetAttribute("State", newState)
	return true
end
if player:GetAttribute("State") ~= States.Idle then return end
if not SetState(player, States.Attacking) then return end
1 Like

Yo did u eventually implement this state module into your combat system?

Hello, yes, I have implemented this into my combat system with some changes

U Got dIscord so i can talk to u on there?