Enemies look at player script not working

i have a script that rotate the enemies to left or right base on where the player is from the object space

local TagService = game:GetService("CollectionService")
local RunService = game:GetService("RunService")

local Players = game.Players

for _,enemies in pairs(TagService:GetTagged("Enemies")) do
	Players.PlayerAdded:Connect(function(plr)
		plr.CharacterAdded:Connect(function(char)
			RunService.Stepped:Connect(function()
				local PlayerPosition = enemies.HumanoidRootPart.CFrame:ToObjectSpace(char.HumanoidRootPart.CFrame)
				
				if PlayerPosition.Z > 0 then
					enemies.HumanoidRootPart.Orientation = Vector3.new(0,-90,0)
				else
					enemies.HumanoidRootPart.Orientation = Vector3.new(0,90,0)
				end
			end)
		end)
	end)
end

the problem is this:


it seems to be the if else statement but i don’t know how to solve it.

1 Like

Have you tried print debugging? Check if the if statements actually run by adding a print to it.
Also, for your case, can’t you just make use of CFrame.lookAt?

enemies.HumanoidRootPart.CFrame = CFrame.lookAt(enemies.HumanoidRootPart.Position, char.HumanoidRootPart.Position)

And if you still want it to be a rigid “left right” kind of thing, you can round it to the nearest 90 as well.

sorry for the late reply

using Cframe.LookAt did work but I am having an issue with rounding to 90 degree since i’m still a beginner

issue:

the line of code:

local divnumber = Eroot.Orientation.Y / 90
				
Eroot.Orientation = Vector3.new(Eroot.Orientation.X,(90 * math.floor(divnumber)),Eroot.Orientation.Z)

--Eroot is the enemies humanoidrootpart

I’m going to use a really useful custom rounding function:

function round(n, to)
    return math.floor(n/to + 0.5) * to
end
Eroot.Orientation = Vector3.new(Eroot.Orientation.X, round(Eroot.Orientation.Y, 90), Eroot.Orientation.Y)

If it doesn’t work, or if you need me to explain anything, let me know.

i’m not sure if i have to modify anything but its not working

I’m not very sure then, sorry. Perhaps anchoring the model will help?

my bad, i forgot to change these line:

Eroot.Orientation = Vector3.new(Eroot.Orientation.X, round(Eroot.Orientation.X, 90), Eroot.Orientation.Y)

to

Eroot.Orientation = Vector3.new(Eroot.Orientation.X, round(Eroot.Orientation.Y, 90), Eroot.Orientation.Z)

thanks for the help!

also, if possible is there a way to remove the middle frame where the enemies face 180 degrees when the enemies is rotating?


it’s not a big deal but it would be better without it

change the round part from 90 to 180

it didn’t work but that’s ok. Thanks helping me

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.