How to raycast forward from a gui on the player's screen?

I have a recoil system in a gun system I’m working on where a cursor gui that follows that player’s cursor is offset by a certain amount when the gun is fired. I want to sort of raycast forward from the gui to get what would be similar to mouse.Hit.Position but for the cursor gui.
Illustration of what I’m trying to achieve:
ex

I’ve tried doing stuff with camera rightvector and upvector and have searched the devforum for a while but can not find a working solution for what I want. Any help is appreciated. Thanks!

2 Likes

You could try plugging the GUI’s position values into this:
https://create.roblox.com/docs/reference/engine/classes/Camera#ScreenPointToRay

I haven’t used this method in a while, but it should work if you plug the UI’s position into it as the X and Y coordinates. Although it returns a ray apparently, not a raycast…

1 Like

Works perfectly, thanks! Here’s what I came up with with that:

local function GetCursorPos()
	local ray = cam:ScreenPointToRay(cursor.Position.X.Scale*plr.PlayerGui.TPGS.AbsoluteSize.X, cursor.Position.Y.Scale*plr.PlayerGui.TPGS.AbsoluteSize.Y, 1)
	local origin = ray.Origin
	local direction = ray.Direction.Unit*10000
	local params = RaycastParams.new()
	params.IgnoreWater = true
	local raycast = workspace:Raycast(origin, direction, params)
	
	if raycast then
		return raycast.Position
	else
		return direction
	end
end
2 Likes

Hey! What’s the cursor variable ?
Also, is TPGS a Frame ?
Personal use, thanks! :smiley: