I want to make a script where you lock on to the nearest player while holding LeftShift.
The problem is that it does not lock on to the enemy, which means it doesn’t find the enemy. I think that mabe the magnitude does not work since it does not print 1 on line 50.
I don’t know why it does not find the target, since in my other scripts it works.
local player = game.Players.LocalPlayer
local char = player.Character
local Humanoid = char:WaitForChild("Humanoid")
PlayerHRP = char.HumanoidRootPart
local Cam = game.Workspace.CurrentCamera
local run = game:GetService("RunService")
local X = 12
local Focused = false
local input = game:GetService("UserInputService")
input.InputBegan:connect(function(k)
local key = k.KeyCode
if key == Enum.KeyCode.LeftShift then
Focused = true
Cam.CameraType = "Scriptable"
end
end)
input.InputEnded:connect(function(k)
local key = k.KeyCode
if key == Enum.KeyCode.LeftShift then
Focused = false
Cam.CameraType = "Custom"
end
end)
local function findTarget()
local dist = 100
local Target = nil
for i,v in pairs(game.Workspace:GetChildren()) do
local human = v:FindFirstChild("Humanoid")
local TargetHRP = v:FindFirstChild("HumanoidRootPart")
if TargetHRP and human and PlayerHRP and v ~= script.Parent.Parent then
if (PlayerHRP.Position - TargetHRP.Position).magnitude < dist then
dist = (PlayerHRP.Position - TargetHRP.Position).magnitude
Target = TargetHRP
end
end
end
return Target
end
local TargetHPR = findTarget()
if TargetHPR then
print(1)
while Focused do
wait()
while(TargetHPR.Position - PlayerHRP.Position).magnitude > 10 and TargetHPR.Parent.Humanoid.Health > 0 do
Health = TargetHPR.Parent.Head:FindFirstChild("BillboardGui")
Health.Enabled = true
local B = TargetHPR.Position
local A = PlayerHRP.Position
local Offset = Vector3.new(5,1,0)
local V = B + ((A + Offset) - B).Unit * ((A - B).Magnitude + X)
Cam.CFrame = CFrame.new(V, B)
run.RenderStepped:Wait()
end
end
end
