Basically, I want the guard to face the player while they shoot, even if the player is on another height. Currently, I am simply setting the NPC’s CFrame by using CFrame.lookAt(at, lookAt) in a while wait() do loop. This is very performance-inefficient and causes the NPC to topple over as well:
I’ve thought of ignoring the Y component of the lookAt, but that might make the NPC aim at the wrong direction. Is there a way to a) make the NPC turn smoothly, b) not use while wait() do, and c) make the NPC face the player correctly?
Code:
...
elseif state == Enumerations.GuardState.ATTACK then
local result: RaycastResult
local distance: Vector3
for _, player in Players:GetPlayers() do
result, distance = raycastToPlayer(player)
if not result and ((withinFOV(distance) and distance.Magnitude <= MAX_RANGE)
or distance.Magnitude <= PHYSICAL_RANGE) then
lastKnownPos = player.Character.Head.CFrame.Position
if not isFiring then
isFiring = true
firingCoro = task.spawn(function()
while wait(60 / firearm_data.statistics.rpm) do fire() end
end)
facingCoro = task.spawn(function() while wait() do
guard.HumanoidRootPart.CFrame = CFrame.lookAt(
guard.HumanoidRootPart.CFrame.Position,
player.Character.HumanoidRootPart.CFrame.Position
)
end end)
end
break
end
end
if result or not withinFOV(distance) or distance.Magnitude > MAX_RANGE then
isFiring = false
if firingCoro then task.cancel(firingCoro) end
if facingCoro then task.cancel(facingCoro) end
if lastKnownPos then
followPath(guard, path, lastKnownPos)
end
end
end

