Cctv follow player?

So what i want to achieve is cctv[Picture Below] follow Player[Video below]

Cctv:

Just like this:
robloxapp-20210926-1613156.wmv (1.7 MB)

This is the script of the dummy:

local neck = workspace.Dummy.Head.Neck
local NPC = workspace.Dummy

function getClosestPlayer()
	local closest_player, closest_distance = nil, 30
	for i, player in pairs(workspace:GetChildren()) do
		if player:FindFirstChild("Humanoid") and player ~= NPC then
			local distance = (NPC.PrimaryPart.Position - player.PrimaryPart.Position).Magnitude
			if distance < closest_distance then
				closest_player = player
				closest_distance = distance
			end
		end
	end
	return closest_player
end

local cframe0 = neck.C0
while true do
	local player = getClosestPlayer()
	if player then
		local is_in_front = NPC.PrimaryPart.CFrame:ToObjectSpace(player.PrimaryPart.CFrame).Z < 0
		if is_in_front then
			local unit = -(NPC.PrimaryPart.CFrame.p - player.PrimaryPart.Position).unit
			neck.C0 = cframe0 * CFrame.new(Vector3.new(0, 0, 0), unit) * CFrame.Angles(0, -math.rad(NPC.PrimaryPart.Orientation.Y), 0)
		end
	end
	wait()
end

And i tried to modify it and put in the cctv, This is the script:

local cctv = script.Parent
local motor6d = script.Parent.CameraCase.Motor6D
function getClosestPlayer()
	local closest_player, closest_distance = nil, 30
	for i, player in pairs(workspace:GetChildren()) do
		if player:FindFirstChild("Humanoid") and player ~= cctv then
			local distance = (cctv.CameraCase.Position - player.PrimaryPart.Position).Magnitude
			if distance < closest_distance then
				closest_player = player
				closest_distance = distance
			end
		end
	end
	return closest_player
end
local cframe0 = motor6d.C0
while true do
	local plr = getClosestPlayer()
	if plr then
		local is_in_front = cctv.CameraCase.CFrame:ToObjectSpace(plr.PrimaryPart.CFrame).Z < 0
		if is_in_front then
			local unit = -(cctv.CameraCase.CFrame.p - plr.PrimaryPart.Position).unit
			motor6d.C0 = cframe0 * CFrame.new(Vector3.new(0, 0, 0), unit) * CFrame.Angles(0, -math.rad(cctv.CameraCase.Orientation.Y), 0)
		end
	end
	wait()
end

So yea, I hope someone can help me with this.
Thanks!!</3

1 Like

I think you shouldn’t be using this in the both script, instead use

function onRepeat()
local plr = getClosestPlayer()
	if plr then
		local is_in_front = cctv.CameraCase.CFrame:ToObjectSpace(plr.PrimaryPart.CFrame).Z < 0
		if is_in_front then
			local unit = -(cctv.CameraCase.CFrame.p - plr.PrimaryPart.Position).unit
			motor6d.C0 = cframe0 * CFrame.new(Vector3.new(0, 0, 0), unit) * CFrame.Angles(0, -math.rad(cctv.CameraCase.Orientation.Y), 0)
		end
	end
	wait()

end
game:GetService("RunService").RenderStepped:Connect(function(onRepeat)
1 Like

There’s a error tho, RenderStepped event can only be used from local scripts. Should i change the Script to LocalScript?

Yes, if it would only focus on one player.

1 Like

Nope, doesn’t work :frowning_face:

(brrrbrbrbr)