Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Cloning Character in Viewport Looks Choppy?

Asked by 2 years ago

Hey everyone, I’m having some issues with rendering my character in a viewport frame. I’d like it to look smooth, although for some reason it looks extremely choppy. I followed a tutorial on youtube to get it in the current state.

Here is what it currently looks like.

Here is what it looks like in the explorer.

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RemoteEvents = ReplicatedStorage:WaitForChild("RemoteEvents")

local RunService = game:GetService("RunService")
local TimeFunction = RunService:IsRunning() and time or os.clock
local viewportFrame = script.Parent:WaitForChild("ViewportFrame")

local running = script.Parent:WaitForChild("Running")
local modelName = script.Parent:WaitForChild("ModelName")
local gameWorkspace = game:GetService("Workspace")
local currentModel = nil
local cam = Instance.new("Camera", script.Parent)
local elapsedTime = 0
local rate = 1 / 60 -- 30 times a second

local function modifyViewport(currentModel, deltaTime)
    local model = viewportFrame:FindFirstChild("Model")
    if(model) then
        model:Destroy()
    end

    local newModel = Instance.new("Model")
    newModel.Name = "Model"
    newModel.Parent = viewportFrame
    -- Replaces with current model
    for i,v in pairs(currentModel:GetChildren()) do
        local v2 = v:Clone()
        if(v2:IsA("Script") or v2:IsA("LocalScript") or v2:IsA("ModuleScript")) then
            v2:Destroy()
        else
            v2.Parent = newModel
            if(v2:IsA("Humanoid")) then
                v2.DisplayDistanceType = Enum.HumanoidDisplayDistanceType.None
            end
        end


    end
    viewportFrame.CurrentCamera = cam
    cam.CFrame = ((currentModel.PrimaryPart.CFrame * CFrame.Angles(math.rad(15),math.rad(180),0)) * CFrame.new(0,1,4)) + cam.CFrame.LookVector * deltaTime  
end

game:GetService("RunService").RenderStepped:Connect(function(deltaTime)

    elapsedTime += deltaTime

    rate = 60 / (1/deltaTime) * 0.01

    if(running.Value) then
        local currentModel = gameWorkspace:FindFirstChild(modelName.Value) or gameWorkspace.NPCs:FindFirstChild(modelName.Value)
        if(currentModel) then
            local success, errorMessage = pcall(function()
                if elapsedTime >= rate then
                    modifyViewport(currentModel, deltaTime)
                    elapsedTime -= rate
                end
            end)
            if not success then
                warn(errorMessage)
                running.Value = false
            end
        else
            running.Value = false
        end
    end
end)

Here is the script that runs it.

What can I do to fix this? I’ve been trying to mess around with delta time to see if that would fix the issue, although I’m not sure exactly what I’m doing to be honest.

Thanks!

Answer this question