- Home /
How to make the npc face the player.
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)
Answer by VesuvianPrime · Sep 11, 2014 at 05:02 PM
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 tried this script just to test it. I put it in the Update(), but it won't run because there's an error. Could you please share the rest of the relevant code?
This is a good answer, for anyone who wants to know how to further update the rotation of the NPC after getting the target value, here is what I did below. Of course, playerPos and npcPos must be given the transform.position of their respective GameObjects.
float smooth = 5.0f; //Sets the speed at which the NPC rotates towards you to keep contact Vector3 playerPos; Vector3 npcPos; Vector3 delta = new Vector3(playerPos.x - npcPos.x, 0.0f, playerPos.z - npcPos.z); Quaternion target = Quaternion.LookRotation(delta); transform.rotation = Quaternion.Slerp(transform.rotation, target, Time.deltaTime * smooth);
Answer by PokerBob · Oct 21, 2019 at 09:10 AM
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;
}
}
Your answer
Follow this Question
Related Questions
Face to direction, in a Mario Galaxy style game? 1 Answer
Rotating character based on joystick angle, at an angle 0 Answers
Objects rotate but remain on the original axis... 0 Answers
Weird GetAxis behavior 0 Answers
Rotation facing the right way problem 0 Answers