Question may seems silly, but I am failing to rotate the npc using only single (vertical) axis. How do I freeze two axis’s while rotating the object to face a Vector3 point?
I tried to rotate it around the y axis by the angle between transform.forward and direction to the Vector3 point, but the angle is always a positive value, so npc constantly rotates like a bloody carousel)
You should take a look at the documentation for Quaternions.
Quaternions look difficult at first, but when you learn how to use them and WHY to use them, they will make your life a million times easier.
In your specific case, you can get the rotation for your NPC by doing:
Vector3 playerPos;
Vector3 npcPos;
Vector3 delta = new Vector3(playerPos.x - npcPos.x, 0.0f, playerPos.z - npcPos.z);
Quaternion rotation = Quaternion.LookRotation(delta);
I was just looking for a simple way how to do this and found your answer, which works great, thanks. for anyone else who is having trouble understanding how to implement it, what i did was add a script to each NPC gameobject I wish to keep looking at us (as below). BTW ‘ThePlayer’ is a static reference to the FPS controller
using UnityEngine;
public class FacePlayer : MonoBehaviour
{
void Update()
{
Vector3 playerPos = GameManager.ThePlayer.transform.position;
Vector3 npcPos = gameObject.transform.position;
Vector3 delta = new Vector3(playerPos.x - npcPos.x, 0.0f, playerPos.z - npcPos.z);
Quaternion rotation = Quaternion.LookRotation(delta);
gameObject.transform.rotation = rotation;
}
}
transform.LookAt(PlayerPos);