I’m trying to create a simple AI where upon spotting the player in a field of view would turn to face them and back away while maintaining a flee path. I’ve modified the flee path so that the AI only makes a new flee path when the player gets too close, but I can’t seem to figure out how to keep the AI facing the player, and make it move backwards basically. I tried altering the rotation of just the game model, but the AI really didn’t like that.
Here’s what I have so far that’s functional:
I’ve been stuck on this for 8 hours, someone please help.
public GameObject Eyes;
public float lookSpeed = 50f;
public float lookRadius = 100f;
public float fleeRadius = 20f;
public float maxFOVAngle = 60.0f;
public Vector3 visionOffset;
public int searchLength = 400;
public float fleeStrength = 1;
public int pathSpread = 4000;
private GameObject player;
public bool inSight = false;
IAstarAI ai;
void Start () {
player = GameObject.FindGameObjectWithTag("Player");
ai = GetComponent<IAstarAI>();
}
void Update () {
//-Sight Code-
Vector3 fovRadius = Eyes.gameObject.transform.forward * lookRadius;
float targetAngle = Vector3.Angle(player.gameObject.transform.position - Eyes.gameObject.transform.position, fovRadius);
//Distance between the player and the fleeing entity
float distance = Vector3.Distance (transform.transform.position, player.transform.position);
//If the angle from the player to the fleeing is within the field of view of the fleeing:
if (targetAngle < maxFOVAngle)
{
RaycastHit hit;
//Draw a Ray to the player. Is the player obstructed? If yes, the player is not in sight. If no, then the player is sighted.
if (Physics.Raycast(Eyes.transform.position, player.transform.position - Eyes.transform.position + visionOffset, out hit, lookRadius))
{
if (hit.collider.CompareTag("Player"))
{
inSight = true;
}
else
{
inSight = false;
}
}
}
//-Movement and Reactions-
Vector3 thePointToFleeFrom = player.transform.position;
if(inSight)
{
ai.canSearch = false;
Debug.DrawRay(Eyes.transform.position, player.transform.position - Eyes.transform.position + visionOffset, Color.red);
ai.rotation = Quaternion.RotateTowards(ai.rotation, Quaternion.LookRotation(-transform.forward), Time.time * (lookSpeed / 100));
FleePath path = FleePath.Construct (transform.position, thePointToFleeFrom, searchLength);
path.aimStrength = fleeStrength;
path.spread = pathSpread;
if (!ai.pathPending && (distance < fleeRadius || !ai.hasPath))
{
ai.SetPath(path);
ai.canSearch = true;
}
}
if(!inSight)
{
Debug.Log("Out of sight");
}
}