Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

how do i detect if a player comes NEAR something without touching?

Asked by
Jumbuu 110
7 years ago

all help is valued, cuz i feel like i was loosing hair on dealing with this question. does it have something to do with the positions and magnitude?

2 answers

Log in to vote
4
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
7 years ago
Edited 7 years ago

First off, you gotta know how magnitude works.

Magnitude

Magnitude is the length of a vector. If you get the magnitude of a vector, you are receiving the length of that vector, in studs.

local vec = Vector3.new(0,5,5) --Define a vector
print(vec.magnitude) --Print out the magnitude
--> 7.071067810058 --Receive the length

Now, if you subtract two vectors from eachother, it creates a vector that is the length of the distance between them. Get the magnitude of that vector and you receive a number, approximately how far away the two vectors are from eachother.

local v1 = Vector3.new(0,0,-5) --First vector
local v2 = Vector3.new(0,5,5) --Second vector
local dist = v2 - v1  --Create another vector, of the difference between the two
print(dist.magnitude); --Now get the distance of it, using magnitude.
--> 11.180339813232

Applying to your code

In a script inside the player's Character, use magnitude to check the distance from the torso to the object. If the number you get back is lower than your desired distance, then the player is near your object.

local part = workspace.Part --Define your part!!
local tor = script.Parent --This is the torso
local near = 5 --The distance, in studs, how far 'near' is.

while wait(1) do
    --Get the distance
    local dist = (tor.Position - part.Position).magnitude
    --Check if it's near
    if dist <= near then
        --If so, announce it in the output.
        print(tor.Parent.Name.." is near "..part.Name.." !"
    end
end
1
Why don't you use the :DistanceFromPlayer(part.Position) method? GoldenPhysics 474 — 7y
Ad
Log in to vote
2
Answered by 7 years ago
local door = script.Parent

while true do
    for i,v in pairs(game.Players:GetChildren()) do
        if (v.Character.Torso.Position - door.Position).magnitude <= 20 then
            door.Transparency = (v.Character.Torso.Position - door.Position).magnitude/15
        else
            door.Transparency = 1
        end
    end
    wait()
end

heres an other example it will make the door get more and more visible when the players torso get closer to it and will fade out when the player walks further away

Answer this question