How to increase the accuracy of raycast with Mouse.Hit.Position

In the code below, I create a block to be the origin of the raycast and I subtract the mouse position by the origin, the script works perfectly, but I wanted it to be more accurate. Sometimes I have to “raise” the mouse pointer for it to hit what I want, and I just want to increase the accuracy, my code:

if CooldownTP then return end
		
		local Block = Instance.new("Part", workspace)
		Block.CFrame = Player.Character.Head.CFrame * CFrame.new(0, 0, -2)
		Block.Name = "RAIO"
		Block.Size = Vector3.new(0.4, 0.4, 0.4)
		Block.Anchored = false
		Block.Color = Color3.new(0.333333, 1, 0)
		Block.Material = Enum.Material.Neon
		Block.CanCollide = false
		Block.Transparency = 1

		local Weld = Instance.new("WeldConstraint", Player.Character.Head)
		Weld.Part0 = Player.Character.Head
		Weld.Part1 = Block

		local StartPos = Block.Position
		local EndPos = Mouse.Hit.Position

		local Params = RaycastParams.new()
		Params.FilterType = Enum.RaycastFilterType.Exclude
		Params.FilterDescendantsInstances = {Player.Character}

		local ray = workspace:Raycast(StartPos, (EndPos - StartPos * 1.1), Params)

		if ray and ray.Instance then
			if ray.Instance.Parent:FindFirstChild("HumanoidRootPart") then
				CooldownTP = true
				local Position = ray.Instance.Parent:FindFirstChild("HumanoidRootPart").CFrame * CFrame.new(0, 70, 5)
				Player.Character.HumanoidRootPart.CFrame = Position
				local SmashAnim = Player.Character.Humanoid:LoadAnimation(Animations.Smash)
				SmashAnim:Play()
				SmashAnim:GetMarkerReachedSignal("SMASH"):Connect(function()
					Remotes.FireEvent:FireServer("TPSkill")
				end)
				task.wait(6)
				CooldownTP = false
			end
		end

You will not get any more “accurate” than that. Raycasts are of finite length on purpose. The accuracy of the raycast doesn’t change with the length of the ray, the only difference it may have is in the performance impact it may have, however this is very minor and you probably shouldn’t bother yourself with it unless you’re doing 10k+ studs raycasts

1 Like

However I do recommend to instead use a Unit of the direction vector and multiply it with a constant scalar value.

1 Like

Thanks! Apparently it’s working better now.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.