Created
December 4, 2017 22:59
-
-
Save Fraktality/31bc9cb5abf2af4340cd3a6a775c616d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Both OOP and Rx solution here:
https://gist.github.com/Quenty/803e0a6f36804e327c60347e52803359