✓ Accepted answer
The magnitude of a Vector is its length, simple as that. This has an interesting property when combined with subtracting two Vectors in that it becomes the distance between those two Vectors.
(g[i].Torso.Position.Z - x.Position.Z) is a Number, not a Vector, and thus it does not have a 'magnitude' in that sense: the number itself is the magnitude!
If I understand your code, you want to deal 25 damage to Players within 50 studs of 'x', discounting any vertical difference. To do that, you can simply create a new pair of Vector3s to subtract and get the magnitude you want. (Additionally, this code uses a generic for loop as opposed to your numeric for):
function damage()
for _, v in ipairs(game.Workspace:GetChildren()) do
if v:FindFirstChild("Humanoid") and v:FindFirstChild("Torso") and v.Humanoid.Health > 0 then
local a = Vector3.new(x.Position.X, 0, x.Position.Z)
local b = Vector3.new(v.Torso.Position.X, 0, v.Torso.Position.Z)
if (a - b).magnitude <= 50 then
v.Humanoid.Health = v.Humanoid.Health - 25
end
end
end
end
You don't need to use FindFirstChild on the Humanoid the second time, because Lua's and and or operators are short-circuited. Basically, in the case of and, if the first check there is false or nil, the rest aren't evaluated. So, if v:FindFirstChild("Humanoid") returns something, we know that v.Humanoid exists, and can use it later in the same conditional.
1 comment
Okay, thank you for your help! Also the reason I added the 2nd check for a humanoid is because there's a tool that changes the players Humanoids name and I wasn't sure if it would glitch in anyway if a player used it.