If Player Looks At Enemy Script

Hey guys,
i’ve tried alot of things but i can’t get it to work. In my script it measures the distance between the enemy and the player, if the player is close to the enemy and he/she looks at the enemy something happends. And that is what i can’t get to work. I’m sorry if this is big ask, but i’ve been searching and testing scripts for a long time now and without sucesss. Thanks in advance.

if (dist < 20 && *looking at enemy*)
{
debug.log("Play an audio track that pauses so it doesn't repeat right after being looked at again")
}

Hello Ruffy789,

Have you tried using a Raycast ? You could start a ray from your player position (and with his forward direction) and test if the ray hits any enemy. If so, you can play the sound.

Depends on how precise you want the “sight” to be, but for some cases this approach would work.

Thanks guys, i just noticed that i already made an avoidance system using Raycast and didn’t come to the idea to use it for this problem. This is what i figured out:

if (dist < 20 && Physics.Raycast (transform.position, fwd, rayLength) &&!audio.isPlaying) {

audio.PlayOneShot(Scare1);

Debug.Log(“Working”);

}

}

It works but, (Script had bug with audio) I fixed the audio problem by adding !audio.isPlaying. Silly me forgetting syntaxes

Thanks to everyone who helped me.

Here’s the Dot product method. If the dot == 1, then you’re looking at it, if it’s -1 then it’s behind you.

	Transform looker, target;

	void Update()
	{
		if (Vector3.Dot(looker.forward, (target.position - looker.position).normalized) < 0.9f)
		{
			// LOOKER IS NOT FACING TARGET YET
		}
		else
		{
			// LOOKER IS FACING THE TARGET
		}
	}

Vector3.Dot should do the job for you, read the documentation on that for more info.
Hope this helps!