Issues with custom mouse raycasting

Im trying to make a customized version of mouse.Hit.Position.
Im having issues however, the ray being cast in my custom script isnt firing forward at the mouse but instead ends at the camera were it started.

this is the script:

local module = {}

module.FireCamRay = function(plr)
local cam = workspace.CurrentCamera
local mouse = plr:GetMouse()
local params = RaycastParams.new()
local userinput = game:GetService("UserInputService")
local mousepos = userinput:GetMouseLocation()

params.IgnoreWater = false

local mouseray = cam:ViewportPointToRay(mousepos.X, mousepos.Y)
local cfr = CFrame.new(cam.CFrame.Position,mouse.Hit.Position)
local ray = workspace:Raycast(mouseray.Origin,mouseray.Direction * 100,params)
local finalpos = mouseray.Origin + mouseray.Direction.Magnitude * mouseray.Direction.Unit

return finalpos
end

return module
2 Likes

You could use ScreenPointToRay for this:

local part = Instance.new("Part")
part.Anchored = true
part.Parent = workspace

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()

local camera = workspace.CurrentCamera
local length = 500


game:GetService("RunService").RenderStepped:Connect(function()
	local unitRay = camera:ScreenPointToRay(mouse.X, mouse.Y)
	local raycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = {player.Character, part}
	raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
	local raycastResult = workspace:Raycast(unitRay.Origin, unitRay.Direction * length, raycastParams)
	
	if raycastResult then
		part.Position = raycastResult.Position
	end
end)
4 Likes

findpartonray and findpartonraywithignorelist are depreciated, which is why Im trying to use the new castray() function instead.

1 Like