How do I can get the inside magnitude by direction in part? I tried use:
local distance = direction * Part.Size * direction
but it doesn’t work correctly
I need like this:
How do I can get the inside magnitude by direction in part? I tried use:
local distance = direction * Part.Size * direction
but it doesn’t work correctly
I need like this:
Hello there!
You want to do it in a 2D plane? If not you can use raycasting:
local Result = workspace:Raycast.new(bla bla bla)
local Distance = Result.Distance
If you want it in a 2D plane maybe you can do it using trigonometry
a (Distance) = b^2 ((Part side / 2) ^2) + c^2 (Distance from the center to the colision point^2)
The following code might not work, i’m not too good at math
local X = Direction.X
local Y = Direction.Y
if X == 1 or X == - 1 then
local Distance = math.Sqrt(Part.Size.X^2 + (Part.Size.Y * (Y * math.sigh(Y))^2))
else
local Distance = math.Sqrt(Part.Size.Y^2 + (Part.Size.X * (X * math.sigh(X))^2))
end
Hope it helps ;]
How general a solution are you looking for? Do you literally just need the 2D distance from the center of a perfect square to the nearest side for any direction in the plane, or is what you really the distance from any point inside an arbitrary 3D object to the surface, in the some provided direction?
In the worst cases, where the “part” is non-convex or non-manifold mesh, this problem can get pretty difficult.
Thank you for your reply, but I want to do this in 3D and not use the Raycasting
this should work
local function getClosestSurfacePoint(part, point)
local halfSize = part.Size * 0.5
local localPoint = part.CFrame:PointToObjectSpace(point)
local clampedPoint = Vector3.new(
math.clamp(localPoint.X, -halfSize.X, halfSize.X),
math.clamp(localPoint.Y, -halfSize.Y, halfSize.Y),
math.clamp(localPoint.Z, -halfSize.Z, halfSize.Z)
)
if localPoint.X ~= clampedPoint.X then
clampedPoint = Vector3.new(halfSize.X * math.sign(localPoint.X), clampedPoint.Y, clampedPoint.Z)
elseif localPoint.Y ~= clampedPoint.Y then
clampedPoint = Vector3.new(clampedPoint.X, halfSize.Y * math.sign(localPoint.Y), clampedPoint.Z)
elseif localPoint.Z ~= clampedPoint.Z then
clampedPoint = Vector3.new(clampedPoint.X, clampedPoint.Y, halfSize.Z * math.sign(localPoint.Z))
end
return part.CFrame:PointToWorldSpace(clampedPoint)
end
just saying, that it works on the bounding box of the part not the part itself. So meshes won’t work right
there is a get closest point on surface API, I didn’t know that