How do i get an NPC to face at a player by using BodyGyro?

So. I have an NPC that will face at you, but its not smooth. The rotation is very laggy, so how do i recreate this with a body gyro instead? Help will be very much appreciated

Current Script -sorry if my code is a bit messy

NPC = script.Parent
PlayersService = game:GetService("Players")

local MaxRange = 75
local FaceTime = 300

while true do
	local Players = PlayersService:GetChildren()
	wait()
	--print(0)
	for i = 1, #Players do
		local child = Players[i]
		--print(1)
		if child.Character then
			--print("There is a player")
			local character = child.Character
			
			local magnitude = (NPC.HumanoidRootPart.Position - character.HumanoidRootPart.Position).Magnitude
			
			if magnitude <= MaxRange and character.Humanoid.Health > 0 then
				for i = 1, FaceTime do
					wait()
					--print("Facing...")
					local NPCroot = NPC.HumanoidRootPart
					local CharRoot = character.HumanoidRootPart
					
					NPC:SetPrimaryPartCFrame(CFrame.new(
					    NPCroot.Position,
					    CharRoot.Position * Vector3.new(1, 0, 1) +
					        NPCroot.Position * Vector3.new(0, 1, 0)
					))
				end
				--print("Finished facing")
			end
			
		end
	end
end
3 Likes

Take the CFrame that you’re using for the :SetPrimaryPartCFrame method, and set it to the BodyGyro’s CFrame like so:

BodyGyro.CFrame = yourCFrame

Then, I’d probably set the Gyro’s MaxForce for Y to 0, so the NPC remains grounded.

1 Like

you could do this, if you don’t want to use a body gyro in the future

local npc = game.Workspace.Model
npc.PrimaryPart.CFrame = CFrame.new(npc.PrimaryPart.Position, targetRoot.Position)

this will automatically rotate the NPC to look at the target player.

OR

use this in combination with TweenService, and you’ll have a smooth rotation

local ts = game:GetService("TweenService")


function faceTarget(npc, targetRoot)
    local targetCFrame = CFrame.new(npc.PrimaryPart.Position, targetRoot.Position)
    local tween = ts:Create(npc.PrimaryPart, TweenInfo.new(1.25), {CFrame = targetCFrame})
    tween:Play()
end
    






3 Likes

This doesn’t appear to work. I also get no errors.

BodyGyro.CFrame = CFrame.new(NPCroot.Position, CharRoot.Position * Vector3.new(1, 0, 1) + NPCroot.Position * Vector3.new(0, 1, 0))

If you are trying to achieve a smooth like rotation, then you can use TweenService or Body Gyro. Either works. If you are trying to get something to look at another Position or Object or whatever, you need to do:

A.CFrame = CFrame.new(A.Position, B.Position)

So insert a BodyGyro into the NPC’s RootPart and then set the CFrame property of the bodygyro to:

BodyGyro.CFrame = CFrame.new(Root1.Position, Root2.Position)
4 Likes

This appears to work great! Thanks for your help!

1 Like