How to create a ray (raycast) that is directed to the mouse position, but only the Y axis?


I have a question about raycast, namely: how to make raycast move to the mouse position, but on the Y axis, and X, Y depend on the position of the raycast starting point. To make it clearer: let’s say the starting point of raycast is the right hand of the player (character), raycast is directed to the mouse position (as in shooters), but only along the Y axis, and the X, Y axis depends on how the player is rotated. (if it’s still unclear, I’ve drawn a diagram:)

I tried to write code, but it didn’t work out:

local function FIRE(plr,Mouse_Position_Y)
  local origin = workspace.Part
  local beam = origin.beam
  local att1 = origin.Att0.Att1 --Att0 is the beginning of the beam, and Att1 is already the end of the beam.
  local params =
  local deriction = Mouse_Position_Y.Unit * 300
  local result = workspace:Raycast(origin.Position,deriction,params)
   att1.CFrame =, origin.Position)

local function Mouse_Position_Y()
local mouse_pos = game.Workspace.CurrentCamera:ScreenPointToRay(game.Players.LocalPlayer:GetMouse().X,game.Players.LocalPlayer:GetMouse().Y)
return mouse_pos.Direction.y
local plr = game.Players.LocalPlayer
local root = character.PrimaryPart
Thank you in advance for your help!

I would recommend that you use a raycast to get the position of the mouse pointer on the surface in the world.
This can be done by using a RaycastParams object, and then use the Raycast method.
local rayCastParams =
rayCastParams.FilterType = Enum.RaycastFilterType.Blacklist
rayCastParams.FilterDescendantsInstances = {workspace.Part}
local ray = workspace:GetCurrentCamera():ScreenPointToRay(, mouseY),
local hit, pos = workspace:Raycast(ray.Origin, ray.Direction, rayCastParams)

This will return the point where the mouse cursor is on the surface.
This is the method I use to get mouse coordinates in 3D space, and it works well.