How to position a part "over" the mouse cursor?

Hello, i’m trying to make the little red part get on the same position of the mouse cursor by translating it into a Vector3 but I really cannot figure out how. The best I got is making it move slightly towards the mouse but I can’t seem to progress any more.

How it looks like now:

How it should look like:

My current code:

-- all this is wrapped in a RenderStepped event
local PositionOnScreen = UserInputService:GetMouseLocation();
local ViewportMouseRay = CurrentCamera:ViewportPointToRay(PositionOnScreen.X, PositionOnScreen.Y);
local RealDirection =, ViewportMouseRay.Direction.Y, ViewportMouseRay.Direction.Z);
HitPoint = ViewportMouseRay.Origin + RealDirection;
HitPoint =, HitPoint.Y, HitPoint.Z);
Part.Position = HitPoint;

I suggest you look into Mouse.UnitRay and Mouse.Hit.

1 Like

Why not use mouse.Hit.Position?

1 Like

Because it gives me absurd numbers when pointing towards the sky. My map’s length is 256 and I get numbers up to 10 thousands on the Z axis when using Mouse.Hit.

Make a part that goes behind the map, then make it invisible then just have the ray collide on that. It will then be perfectly on the maps axis.

you can always make the Z value a constant

local MouseHit = mouse.Hit.Position *,1,0) +,0,ZConst)

This would make my part always stay on a static position instead of it moving as the Z axis would always be equal to the specified constant.

This is perfect, how did I not think about this. I’m just something else. Thank you. :joy:

1 Like

Your game is 2 dimensional you use 2 axies only