Make player face character to talk to them.

I have a player controlled CharacterController game object, and another (currently stationary) CharacterController game object that I want the player to talk to. I was wondering what the secret was to having making the player face the other character (as opposed to being able to talk to the other character while the player is facing away from the character). I’m thinking raycasting is involved, but I can’t get any of it to work.

Ray ray = new Ray(transform.position, transform.TransformDirection(Vector3.forward));
            RaycastHit hit;
            if (isArmed)
            {
                animation.Play("attack0");
            }
            else
            {
                if (collider.Raycast(ray, out hit, 10))
                {
                    Debug.Log("I see you!");
                    if (hit.collider.gameObject.tag == "NPC")
                    {
                        hit.collider.gameObject.SendMessage("TalkToNPC");
                    }
                }
            }

So, what exactly is my code doing, and what should I change to make the code run correctly?

you could try something like i did

if (Vector3.Distance(turretPoint.position, Player.position) > 1) {
		canGetOn = false;
	}
	
	else if (Vector3.Distance(turretPoint.position, Player.position) < 1) {
		canGetOn = true;
	}

(this is for a turret that the player can get onto)

Look into the Vector3.Dot() function. It can be used to do what you need.

What you want to do is get the dot product of the forward vectors of both the NPC and the player. I’m not exactly sure how it works, some crazy math stuff, but what I do know is that when you get the dot product of the forward vectors of two objects, the result is a number between -1 and 1, and will be exactly -1 when the two objects are directly facing each other.

You probably don’t want to only have the NPC talk if the player and the NPC are DIRECTLY facing each other, because perfectly facing the NPC at the exact degree is too slim of a range. You would want a slightly larger range, so we’ll say from -0.8 to -1.0, have the NPC start talking.

So you would do something like this (this would go on the npc):

var player : GameObject;

function Update(){

	var myForward = transform.TransformDirection(Vector3.forward);
	var playerForward = player.transform.TransformDirection(Vector3.forward);
	var dotProduct = Vector3.Dot(myForward,playerForward);
	
	if(dotProduct < -0.8){
		StartTalking();
	}
	
}

Thanks for the help, guys. It worked!