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

Specifying a player with certain conditions?

So I've finally figured out tables (yay!!). I wanted to specify a certain player from the players service based on these certain conditions:

  1. the player is ~= nil
  2. the players position/CFrame is CLOSEST to a certain part than all the other players
  3. the players health is ~=0

Ive converted the the list of players into a table. I'm iterating through ll the values, but i'm stumped on how to compare one of the properties of a table value to the rest of the values. Here's what I got so far.

wait(1)
players = game.Players:GetChildren()
for i,v in pairs(players) do
	if v.Character.Torso.CFrame-BLANK then
		--do stuff
	end
end

I want BLANK to stand for all the other players positions. I'm trying to specify the player closest to a part.

HALP!!!!

2 answers

✓ Accepted answer

To do this, you would use magnitude.

E.G,

print((part1.Magnitude - part2.Magnitude).magnitude)

Prints the distance from part1 to part2.

So, you would implement it like this:

function getMag(p1,p2)
	local num = (p1.Magnitude - p2.Magnitude).Magnitude
	return num
end

wait(1)

players = game.Players:GetChildren()

local chars = {}

for i,v in pairs(players) do
	if otherRequirements then -- your other requirements
		chars[v.Name] = getMag(v.Character.Torso,otherPart) -- your other part here
	end
end

--- this is the comparison vvvv

local smallest = 0
local plr

for key,v in pairs (chars) do
	if smallest == 0 or v < smallest then
		smallest = v
		plr = key
	end
end

print(plr.Name.. " is the closest, with a distance of " ..smallest.. " studs!")

To explain:

  • The function at the top of the code is simply a way to shorten the way of getting the distance between two parts.

  • Line 14 inserts a value into the "chars" table, with a the key being the player's name.

  • The for loop runs through the "chars" table, checking to see if the current value in the "chars" table is smaller than the value "smallest". If it is, it sets "smallest" to that value, and sets the "plr" value to the value's key.

  • Finally, it prints the results.

I hope this helped!

4 comments

0

WOAH!!! This is alot more compicated than I expected. I dont wanna pester you to make a bigger explanation.... I guess whatever you can do to helps.

0

I could do it..

0

Yeah. Do it :~|

0

Wow, now I get it. THX!!!

What you could consider doing is implementing a temporary holding variable. For example:

wait(1)
players = game.Players:GetChildren()
temp = 0

for i,v in pairs(players) do
    if --[[Condition]] then
        if temp > v.Position then
		temp = v.Position
	end

    end
end

So, you would compare the holding variable to the active, and if it's bigger/lower then set it equal to that.

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