ScreenPointToRay ScreenGui Cursor

Howdy. I was wondering If I’m using ScreenPointToRay correctly? My goal is to take the ScreenGui 2D position and fire my projectile in that world direction. Is everything efficient as can be?

function getFireDirection()
	local cursor = gui and gui.Cursor.Frame

	local center = (cursor.AbsolutePosition* 2)/2	
	local x = cursor.AbsoluteSize.X/2
	local y = cursor.AbsoluteSize.Y/2
	local point = camera:ScreenPointToRay(center.X + x, center.Y+ y)
	
	local raycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = {player.Character}
	raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
	
	local raycastResult = workspace:Raycast(point.Origin,point.Direction * 5000,raycastParams)
	
	if not raycastResult then
		return point.Origin + point.Direction * 5000
	else
		return raycastResult.Position,raycastResult.Instance
	end	
end

Seems to work fine. One thing to watch out for: make sure that the aim direction doesn’t change drastically when aiming at a far away part vs aiming at the sky, like could happen if you aimed near the horizon. Almost every third person shooter on Roblox has this issue and it makes aiming feel bad if aiming at a target against the sky.

1 Like