Transform.LookAt to a certain angle.
Hi! I am currently trying to make a creature who's head looks at the player when it is hunting. But the problem is that if the player goes behind the creature, the head snaps backwards and it looks really weird. Is LookAt the most efficient way to get the effect I want? Any help would be welcome, thanks! :)
Answer by Skyppex_ · Sep 13, 2021 at 07:21 AM
you can do a check to see if the player is behind the creature or not. Simply taking the Dot Product between the creatures preferred facing direction and the direction from the creature to the player should give you the information you need. That will give you a value between -1 and 1. 1 if the two directions are exactly the same and -1 if they're exactly the opposite. Then check if the result is above 0 (or any other value... play around with it to see what you like) and if it is you call the LookAt method, otherwise skip it and make the creature look forward. Here is some untested code, hope it gets you closer to your desired result.
public class LookAtPlayer : MonoBehaviour
{
//Drag in the player in the editor for testing. I recommend find a slightly better solution so you can avoid doing this every time you want smth look at the player.
[SerializeField] Transform playerTransform;
private void HandlLookAtPlayer()
{
//Get the dot product
float dotProduct = Vector3.Dot(transform.position, GetDirection(transform.position, playerTransform.position));
if (dotProduct >= .3f)
transform.LookAt(playerTransform);
// else do nothing
}
//Helper method to get the direction from origin to target.
private Vector3 GetDirection(Vector3 origin, Vector3 target) => (target - origin).normalized;
}