Problems with making an enemy look at the player

I’m trying to make an enemy look at the player

The problem is i don’t really know a way to make it constantly look at the player

I tried doing it with a Changed and GetPropertyChangedSignal but neither worked, i also tried doing it with a while wait() loop but it would work only for 1 enemy becouse it never stops looping

I tried searching for a solution online but could only find stuff about NPC enemies

Another problem is that the code would run before the player spawned in

Code:

--Enemy

--	Variables
--		Services
local Players = game:GetService("Players")

--		References
local enemiesFolder = workspace:WaitForChild("Enemies")
local normalEnemyFolder = enemiesFolder:FindFirstChild("NormalEnemy")
local enemies = normalEnemyFolder:GetChildren()


local function lookAt(enemy, character)
	while wait() do
		enemy.Body.CFrame = CFrame.new(enemy.Body.Position, character.PrimaryPart.Position)
	end
end


wait(5)
for _, enemy in ipairs(enemies) do
	local allPlayers = Players:GetPlayers()
	local target = allPlayers[math.random(1, #allPlayers)]
	
	lookAt(enemy, target.Character)
end

Enemies:
Ekrānuzņēmums 2021-07-24 171310

Try using coroutines to run multiple while loops at once.

for _, enemy in ipairs(enemies) do
	local allPlayers = Players:GetPlayers()
	local target = allPlayers[math.random(1, #allPlayers)]
	
	local myCoroutine = coroutine.create(lookAt)
	coroutine.resume(myCoroutine, enemy, target.Character)
end

That seems to have fixed the problem!

1 Like