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 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.
Answer by Nekobolo · Feb 10, 2017 at 07:07 AM
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;
}
Answer by imrankhanswati · Feb 09, 2017 at 09:52 AM
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: https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
and for line cast check this:
https://docs.unity3d.com/ScriptReference/Physics.Linecast.html
hopefully it can help.
Thank you for the response! I have looked into using a Raycast before, in fact I use them for physics ins$$anonymous$$d 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 $$anonymous$$ario World, which hides no matter what it's height is, as long as $$anonymous$$ario 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.