Viewports Not Lining Up

Hey, I’m trying to make something where a flashlight reveals stuff that isn’t there normally. I’m using two viewport frames. One for the darkness, and a smaller one that follows your mouse for a flashlight. If your mouse is at the edge of the screen, both viewport cameras move.
The flashlight viewport also moves its camera according to your mouse position.

That kind of works, however the flashlight viewport doesn’t line up with the darkness one. Any ideas to how to make it do so?

The script isnt the best but yea
Code:

local player = game.Players.LocalPlayer
local cam = game.Workspace.CurrentCamera
local mouse = player:GetMouse()

local DarkViewport = script.Parent:WaitForChild("DarkViewport")
local FlashViewport = script.Parent:WaitForChild("FlashViewport")
local OffsetPart = script.Parent:WaitForChild("CamOffset")

local camOffsetX, camOffsetY = 0, 0
local camSpeed = 25

local function MakeCamera(Viewport)
	local viewportCam = Instance.new("Camera")
	viewportCam.FieldOfView = 50
	viewportCam.Parent = Viewport
	Viewport.CurrentCamera = viewportCam
end
MakeCamera(DarkViewport) MakeCamera(FlashViewport)

local function CheckMouse(dt)
	-- If Mouse is at edge, move camera
	if mouse.X <= 0.1 * cam.ViewportSize.X then
		camOffsetX -= camSpeed * dt
	elseif mouse.X >=  0.9 * cam.ViewportSize.X then
		camOffsetX += camSpeed * dt
	end
	if mouse.Y <= 0.1 * cam.ViewportSize.Y then
		camOffsetY += camSpeed * dt
	elseif mouse.Y >=  0.9 * cam.ViewportSize.Y then
		camOffsetY -= camSpeed * dt
	end
	-- Clamp into bounds
	camOffsetX = math.clamp(camOffsetX, -19, 19)
	camOffsetY = math.clamp(camOffsetY, -9, 9)
	
	-- Background viewport (Moves when mouse is at edge)
	DarkViewport.CurrentCamera.CFrame = OffsetPart.CFrame * CFrame.new(camOffsetX, camOffsetY, 0) 
	
	-- Have to move smaller viewport to mouse, but it doesnt line up
	local addedX = ((mouse.X / cam.ViewportSize.X) - 0.5) * 19 -- what to multiply by?
	local addedY = -((mouse.Y / cam.ViewportSize.Y) - 0.5) * 9 -- same here
	print(addedX, addedY)
	
	FlashViewport.Position = UDim2.new(0, mouse.X, 0, mouse.Y)
	FlashViewport.CurrentCamera.CFrame = DarkViewport.CurrentCamera.CFrame * CFrame.new(addedX, addedY, 0)
end

game:GetService("RunService").RenderStepped:Connect(function(dt)
	CheckMouse(dt)
end)

RBXM File:
flashlight stuffs.rbxm (9.3 KB)

https://gyazo.com/46277a71a866cff7c80666faeedb519b

If you also have any questions, just ask

3 Likes

Another thing is that i think the flash viewport’s size makes the models smaller, if that helps

1 Like