Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Getting only the X and Z axis for Magnitude?

Asked by 8 years ago

So I'm trying to make it so when a player is in range of a part they take some damage, however I can't it only check the X and Z axis. I'm pretty new to using Magnitude and I understand how to use it, however I can't make it only check a certain axis. This is what I have so far:


function damage() g = game.Workspace:GetChildren() for i = 1,#g do if g[i]:findFirstChild("Humanoid") and g[i]:findFirstChild("Torso") and g[i]:findFirstChild("Humanoid").Health >= 1 then if (g[i].Torso.Position.X - x.Position.X).magnitude <= 50 and (g[i].Torso.Position.Z - x.Position.Z).magnitude <= 50 then g[i].Humanoid.Health = g[i].Humanoid.Health - 25 end end end end

1 answer

Log in to vote
2
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
8 years ago

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.

0
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. OneTruePain 191 — 8y
Ad

Answer this question