Help getting distance between whole part and player

So I’m trying to get the distance between an object and a player, but the object is thin and long. Im using magnitude, but magnitude only gets the distance from the center of the part. How would I get the distance from the whole part?


This clip shows me clicking “F” across the whole part but it only detects me being near it at the center of the part.

2 Likes

The easiest thing to do would be to check the sides. You can generate a position for each of the sides by taking the middle (position) ± half of the size of the part in each direction.

local middle = part.Position
local x1 = Vector3.new(middle.X + (part.Size.X / 2), middle.Y, middle.Z)
local x2 = Vector3.new(middle.X - (part.Size.X / 2), middle.Y, middle.Z)
-- And so on for the other dimensions

You could also get the corners of your part by combining the above in two of each of the dimensions.

1 Like

so i would check the magnitude of the those new vectors?

print((x1 - x2).Magnitude)

that should work

Yup. Since you’re not just checking the middle, you would have to check each of the sides to get a better sense of where the player is in relation to the part. Of course, that means checking a lot more distances. But that’s the tradeoff between resolution and speed.

The problem is that x2 only referred to the middle of the part, but he wants to see how close he is to the edges.

2 Likes

Ok so i just wrote everything and it works good, but it only gets the distance from the end points but i want to check the distance between all of the part.

2 different solutions:

You can either get the magnitude by making another part on the surface of that part and check that distance or I am sure you can use trig here then along with some math you can get an accurate distance.

The 2 option is to raycast which is the easiest but it is costly if you want the distance for multiple parts every frame.

1 Like

You can actually use Ray to check if you near to this part by just casting it into part.

local distance = 3.5
local plr = --Player
local part = --Part you want

local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Whitelist
params.FilterDescendantsInstances = {part}

local rayc = workspace:Raycast(plr.Character.HumanoidRootPart.Position, (part.Position-plr.Character.HumanoidRootPart.Position).unit*distance, params)

if rayc then
	--In distance
end

Like I said, if you want a corner, you would have to combine the additions/subtractions:

-- one xy corner:
local xy1 = Vector3.new(middle.X + (part.Size.X / 2), middle.Y + (part.Size.Y / 2), middle.Z)