How would I make a ray can point to the position of a part that's closest to the ray's origin?

What am I trying to do?
I don’t really know how to word what I’m trying to do, I want to raycast towards a part except I want the ray to be able to point to anywhere on that part depending on which is closest to the origin of the ray (instead of just the middle).

What is the issue?
I’m not sure how to make this.

What solutions have I tried so far?
None, I don’t even know how I would look this up so I didn’t see any other posts or any solutions, if there are any, please link them in a reply.

If you’re wondering, this ray would be used to cast to the nearest part (with a certain attribute) towards the player, but I’m not using magnitude to detect if the part is close enough (only to check if it’s the closest), because I want it to not only detect from the middle of the part.

This solution here helps to find the closest point on a part. Using that, we can raycast from the character towards our given closestPart.

local result = RaycastToNearestPoint(char.PrimaryPart.Position, closestPart)

--// From: https://devforum.roblox.com/t/finding-the-closest-vector3-point-on-a-part-from-the-character/130679/3
local function ClosestPointOnPart(Part, Point)
	local Transform = Part.CFrame:pointToObjectSpace(Point) -- Transform into local space
	local HalfSize = Part.Size * 0.5
	return Part.CFrame * Vector3.new( -- Clamp & transform into world space
		math.clamp(Transform.x, -HalfSize.x, HalfSize.x),
		math.clamp(Transform.y, -HalfSize.y, HalfSize.y),
		math.clamp(Transform.z, -HalfSize.z, HalfSize.z)
	)
end

local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Whitelist

local function RaycastToNearestPoint(origin, part)
	raycastParams.FilterDescendantsInstances = part
	
	local result = workspace:Raycast(origin, (origin - ClosestPointOnPart(part, origin)).Unit * 100, raycastParams)
	if result then
		return result
	end
end

I didn’t test this, so If it doesn’t work: try placing a negative sign in front of 100 to reverse the direction of the raycast.

Hope this helps!

1 Like

Yes, it works! Thank you so much for your reply this really helps out! (I did have to make it -100 btw)
This was a lot simpler than I thought, I should learn more math functions.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.