How to make an explosion only detect the single nearest player model?

I’m using the explosion instance to detect an AoE that is supposed to affect the nearest player and summon effects on exclusively them. I’ve looked through other forums and such but all of them were just different enough to mine to have stupidly simple answers

The issue is that (unsurprisingly) the explosion always detects everybody in that radius, and summons those effects on everyone, which is also (unsurprisingly) not what I want.

I have absolutely no idea where to even begin fixing this, I’m sure there’s some kind of math I can do with the distance magnitudes of each detected player, but I can’t think of it myself and would appreciate the help.

1 Like

so i dont have the AOE but I’m gonna assume you have a table of the players detected. if you don’t then I can help beyond that. i just cant write code for something I don’t see

local closest
local plrClosest
local origin -- assume origin is already defined as the point of the explosion, Vector3
for _, player in pairs(TblOfPlayers) do

local dist = math.abs(origin-player.Character.HumanoidRootPart.Position).magnitude 
if not closest then
 closest = dist
plrClosest = player
continue 
end
plrClosest = if dist < closest then player else plrClosest
closest = if dist < closest then dist else closest

end

need to compare closest after choosing not before, sorry, you could rewrite it into a singular if statement too but I didn’t bother

If you are just getting the closest player to the blast zone, get the distance from all players to the blast zone, and get the value that is the lowest, you can use a for loop for this.

local currentPlayer -- to get the player who holds the value
local currentValue = math.huge -- to get all values

for _,p in Players:GetPlayers() do -- Get all Players
    local dist = (area - p.Character:GetPivot().Position).Magnitude -- Get distance
    if currentZone < currentValue then -- Check if the Distance is closer
        currentZone = dist -- new Distance to check for
        currentPlayer = p -- Player who holds value
    end 
end

Essentially, you loop through the current players in the game, get their distances, then compare them with a variable, you have to start at math.huge as the distances could be anything. the lower it gets, the smaller the distance needs to be in order for a new person to be picked

Otherwise, you can grab a random player to pick from that radius, by checking the radius they are in, adding them to a table, then picking a random index.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.