Guidance for Limiting the Ray's Distance

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:
image

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

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.

1 Like

Try using :ScreenPointToRay instead of :ViewportPointToRay.

If that does not work then just cast a ray yourself from LocalCharacter.Head.Position to Mouse.Hit.Position.Unit * MaxDistance

Mind explaining how Vector3.Unit works?

It just normalizes the vector.

I just want to confirm, is it still safe to use the Mouse object from GetMouse? I heard that it is preseded by UserInputService.

Wiki doesn’t say it was “deprecated” by UserInputService at all so use it all you want. USI just provides more functionality I guess?

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)
6 Likes

@SwagMasterAndrew @SilentsReplacement Thank you for the help! Silent’s solution was more detailed and the formula was right.

1 Like

that is good. glad you got help

2 Likes