HELPPP | URGENT Help Needed on a Universal Way to Detect NPC and Client Context For Special Moves

So I’m helping develop a battlegrounds game yes. As I’m not that of an experienced scripter, I’ve come across some issues with input tracking. I’m trying to make a system where on the last attack of the sequence (an M1), you are airborne, you perform a downslam. Similarly, if you were holding jump before the last attack sequence, you perform an uppercut. However, if you meet none of these requirements, then the normal attack will play.

For more context, different characters have different special moves and requirements to meet them, however, most of them relate to input and state changes.

Furthermore, I’ve been brainstorming ways to make this compatible with NPC’S and mobile players. Thank you in advance :smile:

Here is my pre-existing code:

--// Services //
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local TweenService = game:GetService("TweenService")   

--// Folders //
local RepMods = ReplicatedStorage.Modules
	local Manage = RepMods.Management
	local RepUtils = RepMods.Utilities
		local CoreRUtils = RepUtils.Core
	local CombatMods = RepMods.Combat
	local VelocityMods = RepMods.Velocity
	
	
--// Modules //
local Chrono = require(Manage:WaitForChild("Chrono"))
local AnimationManager = require(Manage:WaitForChild("AnimationManager"))
local StateManager = require(Manage:WaitForChild("StateManager"))
local ComboManager = require(Manage:WaitForChild("ComboManager"))
local CooldownManager = require(Manage:WaitForChild("CooldownManager"))
local ValueManager = require(Manage:WaitForChild("ValueManager"))

local CombatUtility = require(CoreRUtils:WaitForChild("CombatUtility"))

local HitboxClass = require(CombatMods:WaitForChild("HitboxClass"))
local HealthModule = require(CombatMods:WaitForChild("HealthModule"))

local RagdollModule = require(VelocityMods:WaitForChild("RagdollModule"))
local VelocityModule = require(VelocityMods:WaitForChild("VelocityModule"))

--// Configs //
local highlightTween = TweenInfo.new(0.5, Enum.EasingStyle.Cubic, Enum.EasingDirection.Out)

local CombatModule = {}

function CombatModule.CheckAttackCompatability(character: Model)
	
	local isCoreState = StateManager.CheckCoreStates(character, "currentState")
	if isCoreState then return false end

	local isOnCooldown = CooldownManager.IsOnCooldown(character, "attack")
	if isOnCooldown then return false end
	
	return true
end

function CombatModule.M1(character: Model, characterName: string?)
	
	local isAttackCompatable = CombatModule.CheckAttackCompatability(character)
	if not isAttackCompatable then return end
		
	local characterName = CombatUtility.GetGuarenteedCharacterName(character, characterName)
	
	StateManager.SetState(character, "currentState", "attack")
	
	local combo = ComboManager.GetCombo(character, "M1") + 1
	local isFinisher = CombatUtility.IsComboFinisher(characterName, combo)
	
	local M1Data = CombatUtility.GetM1Data(characterName, combo)
	local attackSet = CombatUtility.GetCharacterAttackSet(characterName)
	
	local M1Id = attackSet[combo]
	
	local charHrp: BasePart = character:FindFirstChild("HumanoidRootPart")
	
	local plr = Players:GetPlayerFromCharacter(character)
	
	local successReached = false
	local M1Track = AnimationManager.LoadAnimation(character, "M1", M1Id, false, {
		{"Hit", function()
			
			ComboManager.Set(character, "M1", M1Data.TimeBeforeReset, 1)
			successReached = true
			
			local newHitbox = HitboxClass.new({
				SizeOrPart = M1Data.Size,
				Debris = 0.3,
				InitialPosition = Chrono.ChronoServer.GetLatestCFrame(plr) * CFrame.new(0, -2.8, -3),
				SpatialOption = "InBox",
				Blacklist = {character},
				ID = `M1_{character.Name}`,
				VelocityPrediction = true,
				UseLatencyCompensation = true,
				Debug = false,
				LookingFor = "Humanoid"
			})
			
			newHitbox.HitSomeone:Connect(function(hitCharacters: {Model})
				
				HealthModule.Change((-M1Data.Damage * M1Data.DamageMultiplier), hitCharacters)
				CombatModule.Stun(hitCharacters, 0.5)
				
				CombatModule.ApplyHitEffect(hitCharacters)
				
				if not isFinisher then
					
					CombatModule.ApplyHitAnimation(hitCharacters, combo)
					
				else
					local lookVector = charHrp.CFrame.LookVector
					local flatVector = Vector3.new(lookVector.X, 0, lookVector.Z)
					
					RagdollModule.Start(hitCharacters, 2)
					VelocityModule.Apply(hitCharacters, Vector3.one * M1Data.FinalKnockback, 0.3, flatVector)
					
				end
				
			end)
			
			newHitbox:Start()
			
		end}
	}, M1Data.AnimationSpeedModifier)
	
	AnimationManager.waitUntilFinished(M1Track)
	
	StateManager.SetState(character, "currentState", nil)
	
	if isFinisher then
		CooldownManager.SetCooldown(character, "attack", M1Data.FinalCooldown)
		ComboManager.Restart(character, "M1")
		
		
	else
		CooldownManager.SetCooldown(character, "attack", M1Data.CooldownSpeed)
	end
	
end

function CombatModule.Stun(hitCharacters: {Model}, stunTime: number)
	
	for index, hitChar in ipairs(hitCharacters) do
		local currentState = StateManager.GetState(hitChar, "currentState")
		if currentState == "stun" then continue end
		
		StateManager.SetState(hitChar, "currentState", "stun")
		
		local hitHum: Humanoid = hitChar:FindFirstChildOfClass("Humanoid")
		
		ValueManager.SetValue(hitChar, "stunData", {
			WalkSpeed = hitHum.WalkSpeed,
			JumpPower = hitHum.JumpPower
		})
		
		hitHum.WalkSpeed = 0
		hitHum.JumpPower = 0
		
	end
	
	task.delay(stunTime, function()
		for index, hitChar in ipairs(hitCharacters) do
			StateManager.SetState(hitChar, "currentState", nil)

			local hitHum: Humanoid = hitChar:FindFirstChildOfClass("Humanoid")

			local stunData = ValueManager.GetValue(hitChar, "stunData")

			hitHum.WalkSpeed = stunData.WalkSpeed
			hitHum.JumpPower = stunData.JumpPower

		end
	end)
	
end

function CombatModule.ApplyHitEffect(hitCharacters: {Model})
	
	for index, hitChar in ipairs(hitCharacters) do
		
		local newHighlight = Instance.new("Highlight")
		newHighlight.OutlineTransparency = 1
		newHighlight.Adornee = hitChar
		newHighlight.FillColor = Color3.fromRGB(255, 0, 0)
		newHighlight.DepthMode = Enum.HighlightDepthMode.Occluded
		newHighlight.Parent = hitChar
		
		local highlightTween = TweenService:Create(newHighlight, highlightTween, {
			FillTransparency = 1
		})
		
		highlightTween:Play()
		
		task.spawn(function()
			highlightTween.Completed:Connect(function()
				newHighlight:Destroy()
				newHighlight = nil
				highlightTween:Destroy()
				highlightTween = nil
			end)
		end)
		
	end
	
end

function CombatModule.ApplyHitAnimation(hitCharacters: {Model}, combo: number)
	
	local hitAnims = CombatUtility.GetM1HitAnimations()
	local hitId = hitAnims[combo]
	
	for index, hitChar in ipairs(hitCharacters) do
		
		AnimationManager.LoadAnimation(hitChar, "Hit", hitId)
		
	end
	
end

return CombatModule

Please, feel free to give architectural feedback and support or a better code design.

Yea i see the issue , perhaps track the combo keys i.e. you say simultaneous thresholds exists within the same path M1

just example

M1+M1+M1->finalm1 triggers airborne downslam
whereas the other

holding space anytime before finalm1, triggers uppercut at the finalm1

what I’m thinking, is you need a module that is tracking a keylock. what i mean is, you’re wanting to know if the client is holding down a key and you want that information at the finalm1 because it decides which route to take

let me know if I am correct or not and I can provide further on the above.

Not a fan of you slapping ‘HELP URGENT’ in the title when all you’re doing is learning to code.

Hope you find a solution nonetheless.

Yo, took a look at your script. Honestly, the module structure is really clean (nice usage of StateManager/ComboManager separation)

The main issue is that your M1 function is currently “blind” to the context. It triggers the attack but doesn’t know if the player is holding space or floating in the air

To fix this and keep it compatible with Mobile/NPCs, you should add an inputData table as a parameter to your M1 function.

  • For Players: Pass the input state from the LocalScript (e.g., {HoldingJump = UserInputService:IsKeyDown(Enum.KeyCode.Space)}).
  • For NPCs: Your AI script can just manually pass {HoldingJump = true} when you want them to uppercut.

Here is how I would tweak your M1 function to handle the logic branches, take a look:

-- Modified to accept inputData (optional table)
function CombatModule.M1(character: Model, characterName: string?, inputData: table?)
	
	local isAttackCompatable = CombatModule.CheckAttackCompatability(character)
	if not isAttackCompatable then return end
		
	local characterName = CombatUtility.GetGuarenteedCharacterName(character, characterName)
	
	-- // Check Context //
	local hum = character:FindFirstChild("Humanoid")
	local root = character:FindFirstChild("HumanoidRootPart")
	
	-- Use FloorMaterial to check if airborne (easiest way)
	local isAirborne = hum.FloorMaterial == Enum.Material.Air
	
	-- Check if holding jump (Safe navigation in case inputData is nil)
	local isHoldingJump = inputData and inputData.HoldingJump or false
	
	StateManager.SetState(character, "currentState", "attack")
	
	local combo = ComboManager.GetCombo(character, "M1") + 1
	local isFinisher = CombatUtility.IsComboFinisher(characterName, combo)
	
	-- // Determine Variant //
	local attackVariant = "Normal" -- Default
	
	if isFinisher then
		if isAirborne then
			attackVariant = "Downslam"
		elseif isHoldingJump then
			attackVariant = "Uppercut"
		end
	end

	-- NOTE: You'll need to update your CombatUtility to get the specific ID based on 'attackVariant'
	-- For example: GetCharacterAttackSet(name, attackVariant)
	local attackSet = CombatUtility.GetCharacterAttackSet(characterName) 
	local M1Id = attackSet[combo] 
    -- If you have specific IDs for variants, override M1Id here based on attackVariant
	
	local plr = Players:GetPlayerFromCharacter(character)
	local successReached = false

	-- The rest of your animation logic...
	local M1Track = AnimationManager.LoadAnimation(character, "M1", M1Id, false, {
		{"Hit", function()
			
			ComboManager.Set(character, "M1", M1Data.TimeBeforeReset, 1)
			successReached = true
			
			-- Setup Hitbox based on variant logic if needed
			local hitboxPosition = Chrono.ChronoServer.GetLatestCFrame(plr) * CFrame.new(0, -2.8, -3)
			
			local newHitbox = HitboxClass.new({
				SizeOrPart = M1Data.Size,
				Debris = 0.3,
				InitialPosition = hitboxPosition,
				SpatialOption = "InBox",
				Blacklist = {character},
				ID = `M1_{character.Name}`,
				VelocityPrediction = true,
				UseLatencyCompensation = true,
				Debug = false,
				LookingFor = "Humanoid"
			})
			
			newHitbox.HitSomeone:Connect(function(hitCharacters: {Model})
				
				HealthModule.Change((-M1Data.Damage * M1Data.DamageMultiplier), hitCharacters)
				CombatModule.Stun(hitCharacters, 0.5)
				CombatModule.ApplyHitEffect(hitCharacters)
				
				if not isFinisher then
					CombatModule.ApplyHitAnimation(hitCharacters, combo)
				else
					-- // FINISHER LOGIC //
					local lookVector = root.CFrame.LookVector
					local flatVector = Vector3.new(lookVector.X, 0, lookVector.Z).Unit
					
					RagdollModule.Start(hitCharacters, 2)
					
					-- Apply different velocities based on the variant we determined earlier
					if attackVariant == "Downslam" then
						-- Slam them down
						VelocityModule.Apply(hitCharacters, Vector3.new(0, -50, 0), 0.3) 
					elseif attackVariant == "Uppercut" then
						-- Launch them up
						VelocityModule.Apply(hitCharacters, Vector3.new(0, 50, 0) + (flatVector * 10), 0.3)
					else
						-- Normal Finisher
						VelocityModule.Apply(hitCharacters, Vector3.one * M1Data.FinalKnockback, 0.3, flatVector)
					end
				end
				
			end)
			
			newHitbox:Start()
			
		end}
	}, M1Data.AnimationSpeedModifier)
	
	AnimationManager.waitUntilFinished(M1Track)
	
	StateManager.SetState(character, "currentState", nil)
	
	if isFinisher then
		CooldownManager.SetCooldown(character, "attack", M1Data.FinalCooldown)
		ComboManager.Restart(character, "M1")
	else
		CooldownManager.SetCooldown(character, "attack", M1Data.CooldownSpeed)
	end
end

Yes, I was thinking of using this approach, the problem is I just don’t know if it’s scalable to other characters. Other characters might have other requirements but I think this works nevertheless.

Yes. Would you care to elaborate more on your idea? What your saying is a module to track player input? This would be fine, but it doesn’t extend to NPC’S.

This was a module I had made for knowing if LeftControl is being held.. modules that require it can check to see if LCTRL is actively held or not

I know its a lot more… ridiculous… but my module handles multiple platforms. in your case if you only have PC, you could just simply utilize IsKeyDown

ignore the comments of it because its somewhat incorrect, could also make it better.

CurrentPlatformChecker = require(game.ReplicatedStorage:WaitForChild("Modules"):WaitForChild("CurrentPlatformChecker"))

local LCTRLLockData = {
	LCTRLLockActive = false
}


--[[
	Function: LCTRLLock
	Description: Monitors and toggles the LCTRL lock functionality, preventing elevation adjustments while active. 
	Behavior:
	- On "Begin" or "Change" input states:
		- For "KeyboardAndMouse": Activates when LeftControl is pressed.
		- For "Gamepad": Activates when Thumbstick1 is idle (Delta = Vector3.zero) and clicked into socket.
		- For "Mobile": Always activates (button press).
	- On "End" input state:
		- Deactivates the LCTRL lock for all platforms when input ends.
	Dependencies:
	- CurrentPlatformChecker: Determines the current platform and input type.
	Bindings:
	- Action is bound to LeftControl (keyboard) and Thumbstick1 (gamepad), mobile clicks automaticmade button.
	--]]
local function LCTRLLock(actionName, inputState, inputObject)
	local CurrentPlatformData = CurrentPlatformChecker.AssertCurrentPlatform(inputObject)

	if inputState == Enum.UserInputState.Begin then
		if CurrentPlatformData.inputTypeThePlayerIsUsing == "KeyboardAndMouse" then
			if inputObject.KeyCode == Enum.KeyCode.LeftControl then

				LCTRLLockData.LCTRLLockActive = true

			end

		elseif CurrentPlatformData.inputTypeThePlayerIsUsing == "Gamepad" then
			if inputObject.KeyCode == Enum.KeyCode.ButtonL3 then
				
				--dont know if its vec3zero or .z ~= 0
				LCTRLLockData.LCTRLLockActive = true

			end
		elseif CurrentPlatformData.inputTypeThePlayerIsUsing == "Mobile" then
			LCTRLLockData.LCTRLLockActive = true
		end
	elseif inputState == Enum.UserInputState.End then
		if CurrentPlatformData.inputTypeThePlayerIsUsing == "KeyboardAndMouse" then
			if inputObject.KeyCode == Enum.KeyCode.LeftControl then

				LCTRLLockData.LCTRLLockActive = false

			end
		elseif CurrentPlatformData.inputTypeThePlayerIsUsing == "Gamepad" then
			if inputObject.KeyCode == Enum.KeyCode.ButtonL3 then

				LCTRLLockData.LCTRLLockActive = false

			end
		elseif CurrentPlatformData.inputTypeThePlayerIsUsing == "Mobile" then
			LCTRLLockData.LCTRLLockActive = false
		end
	end

end

game.ContextActionService:BindAction("LCTRLLock", LCTRLLock, true,
	Enum.KeyCode.LeftControl) 

local LCTRLLock = {}



LCTRLLock.LCTRLLockData = LCTRLLockData





return LCTRLLock

I see. That’s a very good idea. Input is still the most in problem though. NPC’s don’t have input. I’ve been trying to find a reliable and universal solution that sticks.

Hmm, I don’t know about universal… perhaps prior to entrancy into the func you’d pass a set of keydowns as one of the args…

you have to understand you are asking for userinput and a ai npc neural (when do you choose to uppercut or downslam for npc; neurals) both are different but if you pass args to begin with you’ll have the “universal” method, or some module that fetches that data.

When NPC decided to do M1, fire a BindableEvent to inform it, and process it same as player’s input.

A bindable event for what? This would get really clunky, no?

The scripts for NPC and battle system are different, isn’t it?
When NPC script decided to do M1, use BindableEvent to inform it to battle system.
If the scripts are same, BindableEvent is not necessary.

Do you guys that adding an action function as a parameter and an override table? This would be used by the desktop players, npc’s and mobile players. So basically, if you use the action function, it gives you the character and the combo, then you can check if the combo has reached max, then it would something along the lines of:

—An example for NPC’S!!

CombatModule.M1(character, “John”, function(ComboData, ActionTable)
      if ComboData.CurrentCombo >= ComboData.MaxCombo then

            character.Humanoid:Jump()

      end
end)

This would enable the NPC to get evaluated for a special ending move.

Similarly, you can directly access the Action Table through the Action Function like:


CombatModule.M1(character, “John”, function(ComboData, ActionTable)
     table.insert(ActionTable.State, Enum.HumanoidStateType.Freefall)
end)

Then the special ending move module evaluate the action table instead of the character directly allowing for easy and scalable system for npc’s and players!

They are in the same script and they use the same function, CombatModule.M1()

So, when NPC decide to M1, you can process it same as player input.
Pass necessary information to function

Yes exactly. It’s a good solution because it can scale to all Players and NPC’S.

Are there still problems remaining?

Well I have to implement it and test it but not for now. Don’t worry it won’t be long until I mark as a solution.

When I look at a problem like this, I usually find state machines like Arch to be pretty useful.

local Arch = require("Arch")

local combatMachine = Arch.createMachine({
    id = "combat",
    initial = "Idle",
    states = {
        Idle = {
            OnEntry = function(context)
                context.attackCount = 0
            end,
            events = {
                TransitionToAttack = { target = "Attack" }
            }
        },
        Attack = { 
            OnEntry = function(context)
                context.attackCount += 1
                if (context.attackCount == 3) then
                    -- last attack
                    if (spacebarPressed) then
                        print("uppercut")
                    elseif (airborne) then
                        print("downslam")
                    else
                        print("normal will play")
                    end
                    return
                end

                print("attack " .. context.attackCount)
            end,
            events = {
                TransitionToAttack = { target = "Attack", guards = {
                    function(context)
                        return context.attackCount < 3
                    end
                }},
                after = {
                    {
                        delay = 0.5,
                        target = "Idle"
                    }
                }
            }
        }
    }
})
combatMachine:Start()

Mouse.Button1Down:Connect(function()
    combatMachine:Send("TransitionToAttack")
end)

This is some pretty simple usage, but hopefully you can get a bigger picture. I created two states “Idle” and “Attack”. “Idle” can transition to “Attack” which runs the OnEntry function, incrementing the attackCount. “Attack” has a self-transition to itself which allows you to attack again. It also has an “after” transition which brings you back to “Idle” if you don’t transition within 0.5 seconds.

Once you reach your final attack, you can perform some checks to do a final attack (you can even query previous states if you need something more advanced). There’s even transition “guards” which can prevent a transition from being taken (in this case, if we reach our final attack). And when we enter the “Idle” state, our attack count resets!

There’s a lot more stuff to Arch, but yea. Hopefully this was useful in someway!

This also helps with NPCs and mobile players as you just need to decide what input will transition them to the next state.

This is great! I’ll look further into this but for right now, I’m just trying to find a universal way for my system. Great resource though. Thanks!