how could I make this script multi-threaded using actors?
I’m trying to make a pixel raytracer which performs semi-well.
--!native
local ScreenGui = script.Parent
local Canvas = ScreenGui:WaitForChild("Frame")
local RunService = game:GetService("RunService")
-- Pixel size
local pixelSize = 8
local pixels = {}
local canvasWidth, canvasHeight
local frameCount = 0
local lastUpdateTime = tick()
local function initializePixels()
canvasWidth = math.floor(Canvas.AbsoluteSize.X / pixelSize)
canvasHeight = math.floor(Canvas.AbsoluteSize.Y / pixelSize)
for _, pixelRow in pairs(Canvas:GetChildren()) do
pixelRow:Destroy()
end
pixels = {}
for y = 0, canvasHeight - 1 do
pixels[y] = {}
for x = 0, canvasWidth - 1 do
local pixel = Instance.new("Frame")
pixel.Size = UDim2.new(0, pixelSize, 0, pixelSize)
pixel.Position = UDim2.new(0, x * pixelSize, 0, y * pixelSize)
pixel.BorderSizePixel = 0
pixel.BackgroundColor3 = Color3.new(0, 0, 0)
pixel.Parent = Canvas
pixels[y][x] = {
frame = pixel,
color = Color3.new(0, 0, 0)
}
end
end
end
local function getColor(hit)
if hit then
return hit.BrickColor.Color
else
return Color3.new(0, 0, 0)
end
end
-- Function to cast a ray and get the color
local function raytrace(camera, x, y, aspectRatio, fov)
local screenX = (x / canvasWidth) * 2 - 1
local screenY = (y / canvasHeight) * 2 - 1
screenX = screenX * aspectRatio * math.tan(fov / 2)
screenY = screenY * math.tan(fov / 2)
local rayDirection = (camera.CFrame.LookVector + camera.CFrame.RightVector * screenX - camera.CFrame.UpVector * screenY).Unit
local ray = Ray.new(camera.CFrame.Position, rayDirection * 100)
local hit, hitPosition = game.Workspace:FindPartOnRay(ray)
return getColor(hit)
end
local function updatePixels()
local camera = game.Workspace.CurrentCamera
local aspectRatio = canvasWidth / canvasHeight
local fov = math.rad(120)
local y = 0
local function updateRow()
for x = 0, canvasWidth - 1 do
local color = raytrace(camera, x, y, aspectRatio, fov)
if color ~= pixels[y][x].color then
pixels[y][x].color = color
pixels[y][x].frame.BackgroundColor3 = color
end
end
y = y + 1
if y < canvasHeight then
RunService.RenderStepped:Wait()
updateRow()
else
frameCount = frameCount + 1
local currentTime = tick()
if currentTime - lastUpdateTime >= 1 then
local fps = frameCount / (currentTime - lastUpdateTime)
ScreenGui.FPSCounter.Text = "FPS: " .. math.floor(fps + 0.5)
frameCount = 0
lastUpdateTime = currentTime
end
end
end
updateRow()
end
initializePixels()
RunService.RenderStepped:Connect(updatePixels)
Canvas:GetPropertyChangedSignal("AbsoluteSize"):Connect(function()
initializePixels()
end)
(yes ik its ai generated, I’m just trying stuff out)