Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Could someone please fix this magnitude script?

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

✓ Accepted answer

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

1 comment

0

Great answer, thank you!

This discussion is preserved as it was. New answers, comments, and votes are closed.