Player Turns Around if Another is Behind Them

I am creating a 2D-styled fighting game and what I’m trying to achieve is getting the player to face towards the enemy’s direction constantly (face to the right if the enemy is to the right and vise-versa). I’ve gotten it to work by making the player face the enemy’s HRP position but it’s very buggy and when you go in the middle of your enemy you face the camera which can offset the players which is something I DON’T want in the game. The main thing I’m trying to achieve is make the player face to the right/left depending on where the enemy is and not just directly staring at where the enemy is.

local player = game.Players.LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()
local hrp = char:WaitForChild("HumanoidRootPart")
local faceTowardValue = workspace.Storage:WaitForChild("Values"):WaitForChild("FaceToward")
local lookpart = nil
local rs = game:GetService("RunService")

coroutine.wrap(function()
	rs.RenderStepped:Connect(function()	
		if faceTowardValue.Value then
			if faceTowardValue.Value:FindFirstChild("HumanoidRootPart") then
				lookpart = faceTowardValue.Value.HumanoidRootPart
			end
		else
			lookpart = nil
		end
		--//Changing Look Direction
		if lookpart then
			local chrPos = hrp.Position; local tPos = lookpart.Position
			local modTPos = (chrPos - tPos).Unit * Vector3.new(1,0,1) --mask out the Y axis
			local upVector = hrp.CFrame.UpVector
			local newCF = CFrame.lookAt(chrPos, chrPos + modTPos, upVector) * CFrame.fromAxisAngle(Vector3.new(0, 1, 0), math.pi)
			hrp.CFrame = newCF
		end	
	end)
end)()


If I understand correctly I would do as follows (Pseudo Code):

  1. Inside the RunService check if (Player1.Position.X - Player2.Position.X) is positive or negative.
  2. If positive Player1 looks Right
  3. If negative Player1 looks Left

Change X to Z if that’s the axis you’re using. If you’re using both, then it’s not 2D and you would have to do something different.

For the position Player1 looks at, it can be any position shifted left or right of the player, with the same height (Y axis). I would do hrp ± 5

Try to implement the code but if you don’t understand let me know.

This did the trick perfectly. Thank you so much!

1 Like

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