Untitled

 avatar
unknown
plain_text
19 days ago
2.7 kB
2
Indexable
--!Type(ClientAndServer)

--!SerializeField
local cameras : {GameObject} = nil

local CameraManager = {}

local cameraRequestEvent = Event.new("CameraRequest")
local cameraResponseEvent = Event.new("CameraResponse")

-- Number of cameras available on the server
local cameraCount = 3

-- Method to set the active camera
function CameraManager.SetActiveCamera(index: number)
    for i, camera in ipairs(cameras) do
        if camera then
            camera:SetActive(i == index)
        end
    end
    -- Notify the server about the active camera index
    CameraManager.SendActiveCameraIndexToServer(index)
end

-- Method to notify the server about the active camera index
function CameraManager.SendActiveCameraIndexToServer(index: number)
    cameraRequestEvent:Fire(index)
end

-- Method to randomly change the active camera every 10 seconds
function CameraManager.StartRandomCameraSwitching()
    local function switchCamera()
        if cameraCount > 0 then
            local randomIndex = math.random(1, cameraCount)
            Timer.After(0.1, function() -- Add a 0.1 second delay
                cameraRequestEvent:Fire(randomIndex)
            end)
        else
            print("No cameras available to switch.")
        end
    end

    -- Start the timer to switch cameras every 10 seconds
    Timer.Every(10, switchCamera)
end

-- Server-side initialization
function self:ServerAwake()
    -- Start the random camera switching logic
    CameraManager.StartRandomCameraSwitching()

    -- Listen for camera request events from clients
    cameraRequestEvent:Connect(function(index)
        -- Ensure index wraps correctly using modulo and notify all clients
        local validIndex = (index - 1) % cameraCount + 1
        ServerCameraManager.SetActiveCameraIndex(validIndex)
        cameraResponseEvent:FireAllClients(validIndex)
    end)
end

-- Client-side initialization
function self:ClientAwake()
    -- Listen for camera response events from the server
    cameraResponseEvent:Connect(function(index)
        -- Wrap the received index using modulo for valid camera selection
        local validIndex = (index - 1) % #cameras + 1
        CameraManager.SetActiveCamera(validIndex)
    end)
end

ServerCameraManager = {}

-- Variable to store the active camera index
ServerCameraManager.activeCameraIndex = 1

-- Method to set the active camera index on the server
function ServerCameraManager.SetActiveCameraIndex(index: number)
    ServerCameraManager.activeCameraIndex = index
    print("Active camera index set to: " .. index)
end

return CameraManager
Leave a Comment