How Do I Make A Frame Follow A Vector3?

I have this local script, and a Frame in a ScreenGui in StarterGui. I want the frame to follow a certain Vector3 value, translated from V3 to V2, and clamped to the edges of the screen when the V3 is off-screen. I have some code, and it kind of works, but I cannot figure out the method to make it work correctly.

When it goes off screen it simply does not translate correctly.

	local Players = game:GetService("Players")
	local Client = Players.LocalPlayer
	local Camera = workspace.CurrentCamera
	local Frame = Client.PlayerGui:WaitForChild("ScreenGui"):WaitForChild("Frame")
	local ScreenSize = Camera.ViewportSize
	local LookAt = Vector3.new()

	while task.wait() do

		local PointOnScreen: Vector3, IsOnScreen: boolean = Camera:WorldToViewportPoint(LookAt)
		PointOnScreen = Vector2.new(
			math.clamp(PointOnScreen.X, 0, ScreenSize.X), 
			math.clamp(PointOnScreen.Y, 0, ScreenSize.Y)
		)

		Frame.Position = UDim2.fromOffset(PointOnScreen.X, PointOnScreen.Y)
	end

Current Behavior

Desired Behavior

You can do something like this:

local RunService = game:GetService("RunService")

local targetPosition = workspace.SpawnLocation.Position -- Position that you want the frame to indicate
local currentCamera = workspace.Camera -- Camera
local targetFrame = script.Parent -- The frame that is to be updated

RunService:BindToRenderStep('_updateScreenUI', Enum.RenderPriority.Last.Value, function()
	local worldPoint = currentCamera:WorldToViewportPoint(targetPosition) -- Get point on viewport from a world point
	local viewportSize = currentCamera.ViewportSize -- Get size of screen
	
	local frameOffsetX = viewportSize.X * targetFrame.Size.X.Scale -- Convert scale X to offset
	local frameOffsetY = viewportSize.Y * targetFrame.Size.Y.Scale -- Convert scale Y to offset
	
	targetFrame.Position = UDim2.fromScale(math.clamp(worldPoint.X, 0, viewportSize.X - frameOffsetX) / viewportSize.X, math.clamp(worldPoint.Y, 0, viewportSize.Y - frameOffsetY) / viewportSize.Y) -- Position it
end)

3 Likes

Hey thanks for the help!
Unfortunately, this only works until the point is out of view/behind the camera. At that point I continue to get this unwanted behavior.

https://gyazo.com/8660c7221ce0d0268b860ce8f1e0f8c0