FindPartOnRay registering a 'hit' right a couple of few studs away?

I’m trying to make a custom mouse interaction system using UserInputService. For some reason, FindPartOnRay is registering something intersecting with the ray almost exactly 1 stud away from the ray’s origin.

Here’s my code:

UserInput.InputBegan:Connect(function(Input,GP)
	if not GP then
		if Input.UserInputType == Enum.UserInputType.MouseButton1 then
			local Position = Input.Position
			local PositionRay = Camera:ViewportPointToRay(Position.X,Position.Y)
			local Target,TargetPosition = workspace:FindPartOnRay(PositionRay,Character)
			
			print(Target,TargetPosition,(PositionRay.Origin-TargetPosition).Magnitude)
		end
	end
end)

Every time I click, it prints (split up for readability)

nil
2.08917713, 17.3768654, 6.52677774 (this varies)
1 (can have floating point inaccuracies)

What’s the issue here?
Thanks :wink:

1 Like

Roblox Rays have a length, specified by the magnitude of the direction vector.

When using :ViewportPointToRay, the returned Ray object has a length of 1.

I’d recommend creating a new Ray for the actual raycast using the data from your PositionRay.

For example:

local Length = math.huge

UserInput.InputBegan:Connect(function(Input,GP)
	if not GP then
		if Input.UserInputType == Enum.UserInputType.MouseButton1 then
			local Position = Input.Position
			local ScreenRay = Camera:ViewportPointToRay(Position.X,Position.Y)
			local PositionRay = Ray.new(ScreenRay.Origin, ScreenRay.Direction*Length)
			local Target,TargetPosition = workspace:FindPartOnRay(PositionRay,Character)
			
			print(Target,TargetPosition,(PositionRay.Origin-TargetPosition).Magnitude)
		end
	end
end)
3 Likes

Thanks!

Do you know why this is not on the wiki?

No problem :smiley:

It’s quite hard to find that information at the moment, but it’s on the FindPartOnRay page:

2 Likes

Ok, thanks.