How to detect if ObjectA is looking at ObjectB, and vice versa?

Hi, I’m trying to make a Super Mario World Boo type enemy, but I am having some difficulties trying to get it working.
From what I’ve seen, a lot of people recommend using a Dot Product, and this is the current version of that script I have.

    Vector3 Dis = (player.transform.position - transform.position).normalized;
    float d = Vector3.Dot (Dis, transform.position);
    Debug.Log(d);

However, the dot product returns with values greater than 1 or lower than -1, which I don’t think is correct. The code above is in the enemy script.
Any help is greatly appreciated!

Following the example on [Vector3.Dot][1] your code should be: Vector3 Dis = enemy.transform.forward; float d = Vector3.Dot (Dis, transform.forward); Tranform.forward is the direction a gameobject is facing. So you should compare the direction they're facing for both characters. [1]: https://docs.unity3d.com/ScriptReference/Vector3.Dot.html

2 Answers

2

hello @Nekobolo! I think you can use raycast or line cast to detect objective A is looking at object B.

check this for Ray Cast:https:

and for line cast check this:

hopefully it can help.

Thank you for the response! I have looked into using a Raycast before, in fact I use them for physics instead of RigidBody2D. However, how would it work if the object is say, floating way above the player? The enemy, as described, is similar to the Boo from Super Mario World, which hides no matter what it's height is, as long as Mario looks at it. Unless there's a way to angle the Raycast to always hit the enemy, I'm not too sure if it's quite what I'm looking for.

I ended up solving this by calculating the X coordinate difference between the enemy and player, and then seeing if the player was facing left or right.

Example:

		if (XDif > 0 && player.facingRight == true)
		{
			Debug.Log("CAN'T MOVE");
			speed = 0f;
			facingPlayer = true;
		}