ScreenPointToRay returning wrong rayUnitDirection and origin

So I have this viewport in which I need to raycast to get a part pointed by mouse.

Here is a small code snippet

local function previewTilePositionForPathEditing(x,y)
	local rayUnit = pathEditorFrame.ViewportFrame.Camera:ScreenPointToRay(x,y)
	print(rayUnit.Direction, rayUnit.Origin)
	local raycast = pathEditorFrame.ViewportFrame.WorldModel:Raycast(pathEditorFrame.ViewportFrame.Camera.CFrame.Position, rayUnit.Direction*100)

the x and y coordinates for mouse’s position are correct, I have already checked that.
when I print the rayUnit.Origin, it just prints out ridiculous values, the origin should always be same/near identical, since it all comes from the camera’s position, but it instead varies from

  • when on left side of the viewport, the Z coordinate is at zero
  • when on right side of the viewport, the Z coordinate is around a thousand

The rayUnit.Direction is also totally wrong. In my case, the camera in the viewport has top-down view, so you would expect the direction to be something like (0.2, -0.98, 0.1) - (Basically very small X and Z directions and almost straight line to bottom) but that is not the case, the Y is just around zero, and X,Z are extremely different (between 1 and 0) depending on the cursor’s position in the viewport.

And yes, the raycast always results nil.

I just don’t know what to do anymore, been stuck here for a few hours, ANY help will be really appreciated.

1 Like

Raycasting in viewports is weird since it seems the :ScreenPointToRay doesn’t work from my experience for viewport cameras,

This was the method that worked for me though:

1 Like

I’ve already tried using ViewportPointToRay, but there’s not really much difference, it still returns absurd values

EDIT: nevermind I missunderstood the post you linked, let me try it

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