Detecting other players within range

I was heavily debating this topic, and being a new coder, i think I found a solution but I’m not entirely sure if it would work.

In my game, I want a gui to appear when a certain character comes within range with another character, however, I’m not 100% how to do this.

I’ve worked with magnitudes before, however the magnitudes I’ve worked with are stationary. Any suggestion as to how I would do this? And would this require loops?

Thanks!

This isn’t the most efficient solution, but maybe you could use a ball shaped part with a radius around the character, welded to the torso, and use .Touched to see when another player is in that range.

(Note - On the radius, make sure it is massless and can collide is off)

Constantly check the distance between each character.

Would this be the most efficient way? I was thinking of doing something like that as well, but having a loop constantly running to check all the players’ distances seems like a lot of strain for a script.

@ImTheBuildGuy I feel like .Touched wouldn’t bee all that efficient either since it tends to be glitchy

1 Like

It being a strain would depend on the game. Is your game a huge open-world game, like Starscape? Are there huge amounts of players per server? This might be something you want to check out.

I use something like this this in my game and it checks hundreds of parts (500) with no game lag at all. I set the interval to 2 (2 seconds) but you could bring it down quite a lot. It would feel responsive and not hurt game load.

Assuming you have less than 500 players!

local INTERVAL = 2
local nextStep = tick() + INTERVAL

game:GetService("Heartbeat"):Connect(function(dt)
	
	if (tick() >= nextStep) then
					
		nextStep = nextStep + INTERVAL

		for unused, otherPlayer in pairs (players) do

			local distance = (localPlayer.RootPart.Position - otherPlayer.RootPart.Position).magnitude
			if distance < 50 then
				print(otherPlayer.Name .. " is close")
			end
            
		end	
	end
	
end)

I use t to turn on/off effects like particle effects as the player walks around.

8 Likes

It’s not really going to be a big game, I just kinda want an “Among Us” type killing where they need to be within range of the player.

@jvdad2222 I’ve never seen that before! I think I’ll try it, I’ll let u know if it works thanks!

I believe it’s
game:GetService("RunService").Heartbeat:Connect
and not
game:GetService("Heartbeat"):Connect

1 Like

It doesn’t change the animation whenever im in range