Problems with ViewportPointToRay

I am currently working on a system, and when using ViewportPointToRay, i saw that it was giving some weird results.

Here is my script

local RayParameters = RaycastParams.new()

	RayParameters.FilterType = Enum.RaycastFilterType.Blacklist
	RayParameters.FilterDescendantsInstances = BlackList -- Raycast Paremeters
	
	local Camera = workspace.CurrentCamera
	
	local OriginAndDirection = Camera:ViewportPointToRay(Position.X, Position.Y, Range) --Create the ray cast position and destination
	
	print(OriginAndDirection.Origin, OriginAndDirection.Direction)	
	
	local FinalRay = workspace:Raycast(OriginAndDirection.Origin, OriginAndDirection.Direction, RayParameters)
	
	return FinalRay

My camera is when i fire the script

Where the script places the origin
image

1 Like

I’m not too sure what you’re asking. How are you defining Position? Is it just the mouse? If so, the final ray would just be the result of a 1-stud-long ray in the direction of the camera at the mouse’s X and Y position which is probably nil. Could you show what you’re expecting?

Shouldn’t you be multiplying the direction by 1000 or the range you need?

Sorry for the late response, i was sleeping.

When i define the OriginAndDirection variable, there is a third argument called depth, so i should not need to multiply that by the range i want again.

local OriginAndDirection = Camera:ViewportPointToRay(Position.X, Position.Y, Range)

1 Like

the third argument passed to ViewportPointToRay shifts the origin of the ray from the camera to the specified range, which means that the magnitude value of the distance between the camera and the origin point will be equal to the value of the variable Range


if you want to cast a ray from the camera, you should set Range to 0 and multiply the ray direction by the desired range

local Ray = Camera:ViewportPointToRay(Position.X, Position.Y, 0)
local FinalRay = workspace:Raycast(Ray.Origin, Ray.Direction * Range, RayParameters)
6 Likes

Thank you so much. This helped me out a lot.

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