I’m working on a custom animate script that’ll allow an NPC to change states while still allowing for easy customizability. I put in prints when troubleshooting function issues and now it all works as it should, but I’ve noticed that the safeguards I put in place don’t really stop the functions from spamming itself. Here’s the functional part of the script:
local function onRunning()
print('is running')
if run.IsPlaying == true then return end
idle:Stop()
run:Play(fadeTransitionTime, 10, animations.Run[2])
end
local function onIdle()
print('on idle')
if idle.IsPlaying == true then return end
run:Stop()
idle:Play(fadeTransitionTime, 10, animations.Idle[2])
end
local function onMoveChange()
if humanoid.MoveDirection.Magnitude <=0.1 then
onIdle()
end
end
local function onHeartbeat()
if math.floor(root.AssemblyLinearVelocity.Magnitude) > 0 then
onRunning()
else
onIdle()
end
end
onIdle()
humanoid.Running:Connect(onRunning)
runService.Heartbeat:Connect(onHeartbeat)
Here’s what the output looks like:
As much as it works as it should, ideally the function wouldn’t be spamming itself and I’m looking for a fix. Any help would be appreciated!
You can just have modify the onHeartBeat and onMoveChange functions like this:
local CurrentState = ""
local function onMoveChange()
if humanoid.MoveDirection.Magnitude <= 0.1 and CurrentState ~= "Idle" then
onIdle()
end
end
local function onHeartbeat()
if math.floor(root.AssemblyLinearVelocity.Magnitude) > 0 and State ~= "Running" then
State = "Running"
onRunning()
elseif State ~= "Idle" then
State = "Idle"
onIdle()
end
end
local function onMoveChange()
if humanoid.MoveDirection.Magnitude <=0.1 and currentState ~= 'idle' then
onIdle()
end
end
local function onHeartbeat()
if math.floor(root.AssemblyLinearVelocity.Magnitude) > 0 and currentState ~= 'running' then
currentState = 'running'
onRunning()
elseif currentState ~= 'idle' then
currentState = 'idle'
onIdle()
end
end
but it looks like it now goes back and forth between the states, consequently breaking the animations
I realised I had a logic error in the code. Try this modified onHeartBeat function:
local function onHeartbeat()
if math.floor(root.AssemblyLinearVelocity.Magnitude) > 0 and currentState ~= 'running' then
currentState = 'running'
onRunning()
elseif math.floor(root.AssemblyLinearVelocity.Magnitude) <= 0 currentState ~= 'idle' then
currentState = 'idle'
onIdle()
end
end