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

Why is my camera script flinging the player on activation?

Asked by 3 years ago

Code (script located inside the character):

local camera = workspace.CurrentCamera
camera.CameraType = Enum.CameraType.Custom
local character = script.Parent
local humanoidRootPart:Part = character:WaitForChild("HumanoidRootPart")
local userInputService = game:GetService("UserInputService")

local minDistance = 5
local maxDistance = 15
local starterDistance = 7.5
local lerpSpeed = 0.1

script:WaitForChild("Offset")
script:WaitForChild("TargetOffset")

script.Offset.Value = Vector3.new(0, starterDistance, 0)
script.TargetOffset.Value = script.Offset.Value

userInputService.InputEnded:Connect(function(input, gameProcessed)
    if input.KeyCode == Enum.KeyCode.Z and not gameProcessed then
        if camera.CameraType == Enum.CameraType.Scriptable then
            camera.CameraType = Enum.CameraType.Custom
            camera.CameraSubject = character.Humanoid
        else
            camera.CameraType = Enum.CameraType.Scriptable
            camera.CameraSubject = nil
        end
    end
end)

userInputService.InputChanged:Connect(function(input, gameProcessed)
    if input.UserInputType == Enum.UserInputType.MouseWheel and not gameProcessed then
        local scroll = input.Position.Z
        local currentScroll = script.TargetOffset.Value.Y
        currentScroll -= scroll
        if currentScroll > maxDistance then
            currentScroll = maxDistance
        elseif currentScroll < minDistance then
            currentScroll = minDistance
        end
        script.TargetOffset.Value = Vector3.new(0, currentScroll, 0)
    end
end)
game:GetService("RunService").RenderStepped:Connect(function()
    script.Offset.Value = script.Offset.Value:Lerp(script.TargetOffset.Value, lerpSpeed)
    if camera.CameraType == Enum.CameraType.Scriptable then
        camera.CFrame = CFrame.lookAt(humanoidRootPart.Position + script.Offset.Value, humanoidRootPart.Position)
    end
end)

I’m making a tower defense game for fun and I want the player to activate a “top down view” where the character will be able to see from a bird’s eye perspective. It works, however whenever I activate the camera the player’s character is flung around, killed, and/or just straight up deleted. In attempt to fix this, I tried setting the camera subject to nil when entering the camera mode. I don’t know what’s causing this, if you have any ideas I would like to hear them. Thanks!

Answer this question