How to make a dynamic closest-point tracking system

So what I want to do is a system that always shows where the closest point is on a part:

but as you can see it only works on the right side of the piece, what do you think is the best way to make this system?

Code I’m using:

local RunService = game:GetService("RunService")
local camera = workspace.CurrentCamera
local part = workspace:WaitForChild("Part")

local ball = Instance.new("Part")
ball.Size = Vector3.new(0.2, 0.2, 0.2)
ball.Shape = Enum.PartType.Ball
ball.Color = Color3.new(1, 0, 0)
ball.Anchored = true
ball.CanCollide = false
ball.Material = Enum.Material.Neon
ball.Name = "VisionClosestPoint"
ball.Parent = workspace

local lastPoint
local function getLastPoint(pos)
	local targetPosition = pos
	local dirToTarget = (targetPosition - camera.CFrame.Position).Unit
	local alignment = camera.CFrame.LookVector:Dot(dirToTarget)

	local angle = math.acos(alignment)
	local angleRad = math.rad(math.deg(angle) - 0.1)

	local cameraDir = camera.CFrame.LookVector
	local rotatedDir = (CFrame.fromAxisAngle(Vector3.new(0, 1, 0), angleRad) * cameraDir).Unit

	local origin = camera.CFrame.Position
	local raycastParams = RaycastParams.new()
	raycastParams.FilterType = Enum.RaycastFilterType.Include
	raycastParams.FilterDescendantsInstances = {part}

	local result = workspace:Raycast(origin, rotatedDir * 100000, raycastParams)

	if lastPoint then
		ball.Position = lastPoint
	end

	if result and result.Instance == part then
		lastPoint = result.Position
		task.wait()
		getLastPoint(lastPoint)
	end
end

RunService.RenderStepped:Connect(function()
	getLastPoint(part.Position)
end)

Thank you in advance

1 Like

Lets not reinvent the bysicle please?

2 Likes

Yeeees, it helped me, thanks, but do you know why there is no documentation for this method?

local RunService = game:GetService("RunService")
local camera = workspace.CurrentCamera
local mouse = game.Players.LocalPlayer:GetMouse()
local part = workspace:WaitForChild("Part")

local ball = Instance.new("Part")
ball.Size = Vector3.new(0.2, 0.2, 0.2)
ball.Shape = Enum.PartType.Ball
ball.Color = Color3.new(1, 0, 0)
ball.Anchored = true
ball.CanCollide = false
ball.Material = Enum.Material.Neon
ball.Name = "VisionClosestPoint"
ball.Parent = workspace

RunService.RenderStepped:Connect(function()
	local lookVector = camera.CFrame.LookVector.Unit
	local partPosition = part.Position
	local distance = (camera.CFrame.Position - partPosition).Magnitude
	
	mouse.TargetFilter = ball
	if mouse.Target and mouse.Target == part then
		ball.CFrame =  mouse.Hit
	else
		ball.Position = part:GetClosestPointOnSurface(camera.CFrame.Position + (lookVector * distance))
	end
end)
```