Skip to content

Instantly share code, notes, and snippets.

@Fraktality
Created December 4, 2017 22:59
Show Gist options
  • Save Fraktality/31bc9cb5abf2af4340cd3a6a775c616d to your computer and use it in GitHub Desktop.
Save Fraktality/31bc9cb5abf2af4340cd3a6a775c616d to your computer and use it in GitHub Desktop.
local camera, cameraChanged
local viewport, viewportChanged
-- Challenge:
-- 1. Make `camera' always point to the the current or last known camera.
-- a. Problem: CurrentCamera can be nil.
-- b. Guarantee that `camera' is never nil.
-- 2. Make `viewport' always be the current actual size of the viewport.
-- a. Problem: ViewportSize can falsely report (1,1) before it gets fixed up by RenderPrepare.
-- b. Guarantee that `viewport' is never (1,1).
-- 3. Yield until the above guarantees are met.
-- 4. Don't leak memory.
do
local viewportChangedRaw
local cameraChangedBindable = Instance.new('BindableEvent')
local viewportChangedBindable = Instance.new('BindableEvent')
cameraChanged = cameraChangedBindable.Event
viewportChanged = viewportChangedBindable.Event
local function updateViewport()
local newViewport = camera.ViewportSize
if newViewport ~= viewport and newViewport.X > 1 and newViewport.Y > 1 then
local oldViewport = viewport
viewport = newViewport
viewportChangedBindable:Fire(oldViewport, newViewport)
end
end
local function updateCamera()
local newCamera = workspace.CurrentCamera or camera
if camera ~= newCamera then
local oldCamera = camera
camera = newCamera
cameraChangedBindable:Fire(oldCamera, newCamera)
if viewportChangedRaw then
viewportChangedRaw:Disconnect()
end
viewportChangedRaw = camera:GetPropertyChangedSignal('ViewportSize'):Connect(updateViewport)
updateViewport()
end
end
workspace:GetPropertyChangedSignal('CurrentCamera'):Connect(updateCamera)
updateCamera()
if not viewport then
viewportChanged:Wait()
end
end
-- Tests
print(camera)
print(viewport)
viewportChanged:Connect(function(oldViewport, newViewport)
print('Viewport changed from', oldViewport, 'to', newViewport)
end)
cameraChanged:Connect(function(oldCamera, newCamera)
print('Camera changed from', oldCamera, 'to', newCamera)
end)
@Quenty
Copy link

Quenty commented Mar 28, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment