Okay, so I made a game which I'm not gonna really explain about and I made an animation for movement for one of the npcs. It follows the nearest player, and here's part of the code I have right now: (It's an enemy npc)
while wait() do local player = FindPlayer() if player ~= nil then h:MoveTo(player.Character.HumanoidRootPart.Position) if not walk.IsPlaying and player.Character.Humanoid.Health >= 1 then walk:Play() elseif player.Character.Humanoid.Health <= 0 then walk:Stop() player.Character.HumanoidRootPart:Destroy() end else h:MoveTo(spawnCF.p) end end
Is there any way to detect if the character is moving, and when it does, run the animation?
Yes! Since both desired Characters must have a Humanoid
to function properly, we can use a Signal of this Object universally to provide listeners running your Animation
.
This property is called Humanoid.Running
, it will fire anytime the Humanoid walks. To use this, the Code should be done below.
--// For this example, we will be using the Player, it still works for NPCs though! local Player = game:GetService("Players").LocalPlayer local Character = Player.Character local Humanoid = Character:WaitForChild("Humanoid") local HumanoidRan HumanoidRan = Humanoid.Running:Connect(function() print("Player is walking!") Humanoid.StateChanged:Connect(function(oldState,newState) if (newState == Enum.HumanoidStateType.Seated) then print("Doesn't meet Conditions!") HumanoidRan:Disconnect() end end) end)
See Humanoid.StateChanged for a better understanding!
Hope this helps! If so, don’t forget to accept this answer!. Any more questions? Ask!
This is my whole script (it also makes the humanoid move towards the nearest player):
local h = script.Parent.Humanoid local walkAnimation = script.Walk local walk = h:LoadAnimation(walkAnimation) script.Parent.Humanoid.Running:Connect(function() walk:Play() script.Parent.Humanoid.StateChanged:Connect(function(oldState, newState) if (newState == Enum.HumanoidStateType.Seated) then walk:Stop() end end) end) local torso = script.Parent.HumanoidRootPart local spawnCF = torso.CFrame script.Parent.HumanoidRootPart:SetNetworkOwner(nil) function FindPlayer() for _, v in next, game.Players:GetPlayers() do if v.Character then local char = v.Character if char:FindFirstChild("Humanoid") and char:FindFirstChild("HumanoidRootPart") then local ptorso = char.HumanoidRootPart if (ptorso.Position - torso.Position).magnitude <= 125 then return v end end end end return nil end while wait() do local player = FindPlayer() if player ~= nil then h:MoveTo(player.Character.HumanoidRootPart.Position) if player.Character.Humanoid.Health <= 0 then player.Character.HumanoidRootPart:Destroy() end else h:MoveTo(spawnCF.p) end end