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

Could someone please fix this magnitude script?

Asked by
drew1017 330 Moderation Voter
9 years ago
p = game.Players:GetChildren()
magnitude = (game.Workspace.turret.Position - #p.Character.Torso.Position).magnitude

game:GetService("RunService").RenderStepped:connect(function()
    if magnitude >= 30 then
        #p.Character.Humanoid:TakeDamage(1)
    end
end)

Im making a turret that causes anyone within 30 studs of it to take damage (aesthetics come later). I know im missing something in the script, but im stumped on what it is and it doesen't do anything when im near it. Could someone fix it and explain how I should detect players in the future?

1 answer

Log in to vote
1
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
9 years ago

Your Problem

You're defining magnitude outside of the event! This way the distance will stay the same each time.

Also, you're trying to get the value of each player's distance using game.Players:GetChildren as your p variable. A variable can only hold on to one value at a time, given that it's not a tuple. You have to iterate through each player with a generic for loop then find the distance.

Given that you're going to have to be iterating through each player, then the RenderStepped event is not a good option. Say there's 10 players in the game.. the RenderStepped event yeilds about 1/60th of a second.. so that's 600 iterations per second which will undoubtedly cause un-needed server lag. Just use a while loop, and wait like every .1 seconds.


How to Use the # Operator

The # operater is used to get the length of a string, or table. It returns either the number of characters in the given string, including whitespaces, or the number of indexes in a table. It does not count metatables, or multi dimensional tables.

local tab = {'H','e','l','l',o'}
print(#tab) --> 5
local str = 'Hello'
print(#str) --> 5

So your usage of the # operator doesn't make any sense. There's no need for it at all.


Code

local turret = workspace.turret

while wait(.1) do
    for i,v in pairs(game.Players:GetPlayers()) do
        local tor = v.Character.Torso
        local mag = (tor.Position - turret.Position).magnitude
        if mag <= 30 then
            v.Character.Humanoid:TakeDamage(1)
        end
    end
end
0
Great answer, thank you! drew1017 330 — 9y
Ad

Answer this question