I tried to make an attack that does damage with the help of magnitude. So whenever I press a certain button the player does the animation and makes damage to the nearest enemy.
The problem is that it seems that the magnitude does not detect anything so nothing happens. Whenever I try to run the script this error comes up:
attempt to index local ‘TargetTorso’ (a nil value)
Instead of torso, use humanoidRootPart. It is returning a bodyPart, so I don’t know why you would do bodyPart.Position < 10. What do you expect to happen here?
You could just do takeDamage thing inside the findTarget function. Using an if statement looks like a stretch.
You’re checking the Position value instead of the difference between their positions.
Replace this:
if TargetTorso.Position < 10 then
with this:
if (TargetTorso.Position - PlayerTorso.Position).magnitude < 10 then
You also need to add a check to make sure TargetTorso exists (that’s what your original error is); overall, it would look like this:
local TargetTorso = findTarget()
if TargetTorso then
if (TargetTorso.Position - PlayerTorso.Position).magnitude < 10 then
TargetTorso.Parent.Humanoid:TakeDamage(20)
end
end
Hey super, SUPER sorry about the 2 year bump but I need help that is similar to this post, and it’s that how would I make this work with my code? I’ve been trying a lot and still nothing. THE FOLLOWING CODE USES THE MODULE (“SimplePath”) BUT I DOUBT THAT’S NECESSARY
local SimplePath = require(script.SimplePath)
function findNearestTorso(pos)
local list = game.Workspace:children()
local torso = nil
local dist = 100
local temp = nil
local human = nil
local temp2 = nil
local player = false
for x = 1, #list do
temp2 = list[x]
if (temp2.className == "Model") and (temp2 ~= script.Parent) then
temp = temp2:findFirstChild("HumanoidRootPart")
human = temp2:findFirstChild("Humanoid")
if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
if game.Players:GetPlayerFromCharacter(temp2) and (temp.Position - pos).magnitude < dist then
torso = temp
dist = (temp.Position - pos).magnitude
end
end
end
end
return torso
end
local Dummy = script.Parent
local Goal = Vector3.new()
local Path = SimplePath.new(Dummy)
Path.Visualize = false
Path.Blocked:Connect(function()
Path:Run(Goal)
end)
Path.WaypointReached:Connect(function()
Path:Run(Goal)
end)
Path.Error:Connect(function(errorType)
Path:Run(Goal)
end)
while true do
wait(.2)
local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
if target then
Goal = target.Position
if Goal ~= nil then
Path:Run(Goal)
else
Path:Stop()
end
end
end
--dumb attempt down here--
local TargetTorso = findNearestTorso(script.Parent.HumanoidRootPart.Position)
if TargetTorso then
if (TargetTorso.Position - script.Parent.HumanoidRootPart.Position).magnitude < 10 then
TargetTorso.Parent.Humanoid:TakeDamage(20)
end
end