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

How can I detect if a player is near (as an event), possible? Without using while true do?

If I use while true do, wouldn't it create lag for unnecessary checking every-time? Can someone point me in the right direction? I just need to know what I should do from this point on.

3 comments

0

If a player is near what? I can help with this, but be more specific.

0

Just put in a wait longer than wait(0) and it won't cause lag.

0

If it's just a brick its simple, if its a model its more complicated.

3 answers

✓ Accepted answer

I don't believe there's an event for this, but you can use a loop and if creating a new thread is necessary, coroutines. You can use magnitude to check the distance between two specified parts. For example:

local base = workspace.base
local part = workspace.part
coroutine.resume(coroutine.create(function()
while wait(1) do
print (part.Position - base.Position).magnitude
end
end))
print("bork")

2 comments

0

This seems good for an answer. Thanks, I suppose. It wouldn't create unnecessary lag would it, hm... If you're checking constantly if a player is near something? I hope it doesn't.

0

It shouldn't create toom much. This is a popular method.

You can make an invisible non can collide-able cylinder/sphere and when a player touches it with the touched event you can change a variable to true. When the player leaves the range of nearness (invisible cylinder) you can use the touchended event and change a variable to false. Ex

--Put this script in an invisible non can collideable sphere that surrounds the object that you want to know if the player is near

PlayerIsNear = false

script.Parent.Touched:connect(function()
PlayerIsNear = true
end)

script.Parent.Touchended:connect(function()
PlayerIsNear = false
end)

if PlayerIsNear == true then
--Do whatever you want here

This creates a lot less lag then a loop

There isn't an event, but if you want an alternative method, you can use magnitudes to detect how close the player is to an object. From there you can determine what you want to do with the script. I used this to create a type of radar/ way to find players near you.

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