How can I optimize this code?
Code
function self.lookat()
if not self.rendering then return end
local model = self.model
if not model then return end
local MaxDistance = 100
local HeadVertFactor = 0.6
local BodyHorFactor = 0.5
local BodyVertFactor = 0.4
local UpdateSpeed = 0.3
local HeadHorFactor = 1
local NeckOrgnC0 = self.baseneckc0 --[Get the base C0 to manipulate off of.]
local WaistOrgnC0 = self.basewaistc0
local Torso = self.torso
local Head = self.head
local Neck = self.neck
local Waist = self.waist
local IsR6 = false
if NeckOrgnC0 and WaistOrgnC0 and Torso and Head and Neck and Waist then
local InRange = false
local PCharacter = Player.Character
if PCharacter then
local HRP0 = model:FindFirstChild("HumanoidRootPart")
local HRP = PCharacter:FindFirstChild("HumanoidRootPart")
local PHead = PCharacter:FindFirstChild("Head")
if HRP and HRP0 then
InRange = math.abs((HRP0.Position-HRP.Position).Magnitude) <= MaxDistance
end
if InRange and PHead and not self.gettinghit and not self.emoting then
local TrsoLV = Torso.CFrame.lookVector
local HdPos = Head.CFrame.p
if Neck or Neck and Waist then
local Point = PHead.CFrame.p
local Dist = (Head.CFrame.p-Point).magnitude
local Diff = Head.CFrame.Y-Point.Y
local NewNeckC0 = NeckOrgnC0*CFrame.Angles(-(math.atan(Diff/Dist)*HeadVertFactor), (((HdPos-Point).Unit):Cross(TrsoLV)).Y*HeadHorFactor, 0)
local NewWaistC0 = WaistOrgnC0*CFrame.Angles(-(math.atan(Diff/Dist)*BodyVertFactor), (((HdPos-Point).Unit):Cross(TrsoLV)).Y*BodyHorFactor, 0)
if Waist.C0 ~= NewWaistC0 then
Neck.C0 = Neck.C0:lerp(NewNeckC0, UpdateSpeed/2)
Waist.C0 = Waist.C0:lerp(NewWaistC0, UpdateSpeed/2)
end
end
else
if Waist.C0 ~= WaistOrgnC0 then
Waist.C0 = Waist.C0:lerp(WaistOrgnC0, UpdateSpeed/2)
Neck.C0 = Neck.C0:lerp(NeckOrgnC0, UpdateSpeed/2)
end
end
else
if Waist.C0 ~= WaistOrgnC0 then
Waist.C0 = Waist.C0:lerp(WaistOrgnC0, UpdateSpeed/2)
Neck.C0 = Neck.C0:lerp(NeckOrgnC0, UpdateSpeed/2)
end
end
end
end