ViewportFrame Math

Upon trying to create some kind of “wall-hack” mode for a game I’m making, my first inclination was to use ViewportFrames instead of creating new Instances that would be affected by ROBLOX’s physics engine, so as to cut down on any lag there might be (there’s a possibility that there may be a lot of or none of these ViewportFrames active at any given time in the game).

local viewportFrame = Instance.new("ViewportFrame")
local viewportCamera = Instance.new("Camera", viewportFrame)
local coloredBox = workspace.ColoredBox:Clone() -- coloredbox's primarypart is "Middle", denoting the middle position of the model

viewportFrame.Size = UDim2.new(1, 0, 1, 0)
viewportFrame.BackgroundTransparency = 1
viewportFrame.CurrentCamera = viewportCamera
viewportFrame.Parent = script.Parent

coloredBox.Parent = viewportFrame

local toWorldSpace = workspace.CurrentCamera.CFrame:toObjectSpace(coloredBox.PrimaryPart.CFrame)

viewportCamera.CFrame = CFrame.new((workspace.CurrentCamera.CFrame.p + Vector3.new(toWorldSpace.p)), coloredBox.PrimaryPart.CFrame.p)

This code currently yields this return:
image

As you can see, neither the sizing, rotation, or position of the ViewportFrame’s rendition of the model is entirely correct. My issue is that I don’t know what to try next, or what I may be doing improperly.

There are other ways to achieve this effect than using ViewportFrames, and if you care to, offer your suggestions. But please do offer your knowledge and help, too.

So:

  1. Your ViewportFrame has to cover the entire screen, with the ScreenGui's IgnoreGuiInset property set to false.

  2. You can make the CurrentCamera of the viewport frame the same as the CurrentCamera of Workspace.

  3. You can make the CFrame of the replicated object the same as the CFrame of the one in workspace.

Altogether:

local viewportFrame = Instance.new("ViewportFrame")
local coloredBox = workspace.ColoredBox:Clone()

viewportFrame.Size = UDim2.new(1,0,1,0)
viewportFrame.BackgroundTransparency = 1
viewportFrame.CurrentCamera = workspace.CurrentCamera
viewportFrame.Parent = script.Parent

coloredBox.Parent = viewportFrame

And that should be it, as long as you follow all the points up there.

3 Likes