So, I currently have a game where I need to limit the distance of the ray (like 25 studs of limit). An illustration is like this:

However, there is one problem:
The UnitRay or Camera:ViewportPointToRay gives an offset and it does not point to the mouse’ position (Image below)

Script:

local function RaycastUsingScreenToPoint()
RaycastParam.FilterDescendantsInstances = LocalCharacter:GetDescendants()
local MouseLocation = UserInputService:GetMouseLocation()
local Origin = LocalCharacter.Head.Position -- the character's head is the origin, not the camera
local UnitRay = Camera:ViewportPointToRay(MouseLocation.X, MouseLocation.Y)
local RaycastResult = workspace:Raycast(Origin, UnitRay.Direction * 200, RaycastParam)
local Direction = (Origin - RaycastResult.Position).Magnitude
local Part = Instance.new("Part")
Part.Size = Vector3.new(0.4,0.4,Direction)
Part.CFrame = CFrame.lookAt(Origin, RaycastResult.Position) * CFrame.new(0,0,-Direction/2)
Part.BrickColor = BrickColor.new("Royal purple")
Part.Anchored = true
Part.CanCollide = false
Part.Parent = workspace
end

Is there another way to raycast from the head to the mouse’s direction and limit the distance? This is my first time doing math in Roblox Studio, so I need help with fixing this problem. Thank you.

Vector3.Unit is any vector but unitized (having a magnitude or length of 1). What you can do is get the direction of the ray and unitize it and multiply it by the max distance. That way, since the direction will have a length of 1, you can multiply it by some number to increase it’s length which is what you want.

You can get the direction as follows: endPosition - startPosition and implementing it in your case:

local MAX_DISTANCE = 200
local direction = (mouse.Hit.Position - head.Position).Unit * MAX_DISTANCE
local ray = workspace:RayCast(head.Position, direction, params)