I want a rock monster to follow the player when they enter a certain area and damage the player when the monster touches the player. Kinda like zombies in zombie attack but with a rock instead. I spent an hour trying to figure out why this error is happening:
local char = script.Parent
local humanoid = char:WaitForChild("Humanoid")
local hrp = char:WaitForChild("HumanoidRootPart")
local walkAnim = script:WaitForChild("Walk")
local walkTrack = humanoid.Animator:LoadAnimation(walkAnim)
local dmgAnim = script:WaitForChild("Damage")
local dmgTrack = humanoid.Animator:LoadAnimation(dmgAnim)
local targetPlayer
local dmgAmt = 10
local RunService = game:GetService("RunService")
local triggerPart = workspace.StarterD.Park.Base.RockSpawn
humanoid.Running:Connect(function(speed)
if speed > 0 then
if not walkTrack.IsPlaying then
walkTrack:Play()
end
else
if walkTrack.IsPlaying then
walkTrack:Stop()
end
end
end)
function findNearestPlayer()
local closestDistance = math.huge
local touchingParts = triggerPart:GetTouchingParts()
local plrTouch
for i, player in pairs(game.Players:GetPlayers()) do
for i, v in pairs(touchingParts) do
if game.Players:GetPlayerFromCharacter(v.Parent) then
plrTouch = true
end
end
local distance = (hrp.Position - player.Character.HumanoidRootPart.Position).Magnitude
if distance < closestDistance and plrTouch then
closestDistance = distance
targetPlayer = player
end
end
end
function damagePlayer()
if targetPlayer then
local playerHumanoid = targetPlayer.Character:FindFirstChildOfClass("Humanoid")
if playerHumanoid then
playerHumanoid:TakeDamage(dmgAmt)
dmgTrack:Play()
end
end
end
RunService.Heartbeat:Connect(function()
findNearestPlayer()
if targetPlayer then
humanoid:MoveTo(targetPlayer.Character.HumanoidRootPart.Position)
if (hrp.Position - targetPlayer.Character.HumanoidRootPart.Position).Magnitude <= 3 then
damagePlayer()
end
end
end)
humanoid.Died:Connect(function()
local newChar = char:Clone()
newChar.Parent = char.Parent
char:Destroy()
end)
Try to replace player.Character.HumanoidRootPart.Position to player.Character.PrimaryPart.Position,
The primary part of the character should be the HumanoidRootPart.
Also, check if the character exists by adding an if condtion.
Update: I used a few print statements and the entire code is working fine but there seems to be a problem with this one line local distance = (hrp.Position - player.Character:WaitForChild("HumanoidRootPart").Position).Magnitude
I already checked and yes, it has a primary part and the all the parts except the HumanoidRootPart are not anchored. I also tried using print statements near the .Hearbeat function and I think there’s a problem with humanoid:MoveTo(targetPlayer.Character.HumanoidRootPart.Position)