Trying to return values based on angle of object relevant to player but I can’t get it to do 360 degrees it only does 180. I searched for how to make it 360 degrees online but
still haven’t got it working. I know I need to differentiate between the left side and the right side which is why I added a right bool and the line if (Vector3.Angle(target.right, target.position - target.position) > 90f) right = false; else right = true;
but it always returns right as true, any help would be appreciated.
using UnityEngine;
using System.Collections;
public class EnemyAngle : MonoBehaviour {
public Transform target;
public GameObject player;
public bool right;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
target = player.transform;
}
void Update()
{
Vector3 targetDir = target.position - transform.position;
Vector3 forward = transform.forward;
float angle = Vector3.Angle(targetDir, forward);
if (Vector3.Angle(target.right, target.position - target.position) > 90f) right = false; else right = true;
if (angle < 45.0f && angle > 0)
{
Debug.Log("45");
}
if (angle < 90.0f && angle > 45.0f)
{
Debug.Log("90");
}
if (angle < 135.0f && angle > 90.0f)
{
Debug.Log("135");
}
if (angle < 180.0f && angle > 135.0f)
{
Debug.Log("180");
}
if (angle < 45.0f && angle > 0 && right == true)
{
Debug.Log("225");
}
if (angle < 90.0f && angle > 45.0f && right == true)
{
Debug.Log("270");
}
if (angle < 135.0f && angle > 90.0f && right == true)
{
Debug.Log("315");
}
if (angle < 180.0f && angle > 135.0f && right == true)
{
Debug.Log("360");
}
}
}
There’s a much simpler way to determine whether the angle is to right or to the left when your axes are clearly defined.
When you calculate a Dot Product, two vectors facing within the same 180 degrees of each other result in a positive value, two vectors facing opposite directions are negative and perpendicular vectors results in zero.
How is this relevant? Well, If the dot product of transform.right and targetDir vectors is greater than zero, it’s to the right. If it’s less than zero, it’s to the left. Finally, if it is zero, it’s neither left nor right, but is either exactly in front of or exactly behind instead.
Now, this has nothing to do with why your current setup isn’t working, regardless. Why isn’t yours working at the moment?
Well, it’s due to a simple error:
if (Vector3.Angle(target.right, target.position - target.position) > 90f)
target.position - target.position == Vector3.zero; You’ve been testing the angle between the target’s right and Vector3.zero. You likely should have been comparing between transform.right and targetDir instead.