How to position an Object in a ViewportFrame relative to Mouse position?

I’ve tried looking on the forums to try and find a solution to this, but they’re never directly for this issue.


I need that gray part to be in the middle of the mouse basically.

Im like 90% there but I cant figure out why its like offset from the mouse and i’m honestly just stumped haha. Also tried multiplying the distance by the ray but then it just overexaggerates mouse movement.

	local MousePos = UIS:GetMouseLocation()
	
	local InsetPos = MousePos - Viewport.AbsolutePosition - GuiService:GetGuiInset()
	local X = InsetPos.X / Viewport.AbsoluteSize.X
	local Y = InsetPos.Y / Viewport.AbsoluteSize.Y
	
	local ray = Camera:ViewportPointToRay(X,Y)
	local Position = ray.Origin + ray.Direction
	
	Viewport.MopObject.CFrame = CFrame.new(Position.X,0,Position.Z)

The part will always be along 0 in the Y axis, it should only move X and Z.

Is there some sort of way to do this accurately???

1 Like