I want to detect when a player moves, say, within 20 studs of a part. How would I do this? Are there any methods I could use or is this something that is hard, if not impossible, to do within ROBLOX?
Help much appreciated.
EDIT: I'm aware of .magnitude and how it could be used in this scenario, but as I'd be checking for distances from many parts, I wanted to know if there was an event such as .changed that would fire if the player came within a certain distance of a part.
What you're asking for is indeed very difficult.
Your thing must be done with one line. ONE. LINE. What i said is just a sample of how frustratingly hard it is to get the distance between parts.
The only thing that makes it easier is that there are two ways to get that distance:
.magnitude
This is a Vector3 property, which obtains the distance between the vector and the origin (0,0,0). Chances are, however, you will not want the origin, but the part's position. This is unfortunately quite hard to obtain: Keep up with me here, the method will be very extensive:
You reduct any two Vector3
s and "magnitude" them altogether.
print((workspace.PartA.Position - workspace.PartB.Position).magnitude)
DistanceFromCharacter()
This is a faster, albeit difficult function to use. It is a function that calculates the distance inbetween the player's character's head and the inputted Vector3
.
If the player's character does not exist on that time, it returns 0 instead of breaking the script.
print(game.Players.MasterDaniel:DistanceFromCharacter(workspace.Marios2.Head.Position))
Hopefully this helps, if your mind is not melted already by trying to figure out all of this.
(Moral: Don't underestimate any programming language. That's what i did with Brainfuck (the language, literally) and then i saw a clock that tells the time made with it.)
(Note: I am not making the above up.)
(Note #2: I mean no offense on this answer. The sarcasm on how simple it is is there for entertainment.)
*Edited .magnitude as of 12/12/15.
This tells if your in range of something
brick = (put a location) range = 20 -- the range while true do wait(.1) plrs = game.Players:GetChildren() for i,plr in ipairs(plrs) do if plr.Character ~= nil then tor = plr.Character.Torso if (brick.Position-tor.Position).magnitude <= range then print(plr.Name.." is in range") end end end end
I know this is 3 years later, but this may be helpful to anybody else coming across this issue.
If you want to find when a player is in range of something, with an event.. the only way I have found is touched(). Now what is the efficient way?
Anytime the part in the radius is touched, or touchended run your magnitude script. This way, it won't be going constently, but goes when it is necessary. Dont want to use a part? then have fun running a function constantly :c