I am going to try to explain this in the easiest way. I am making some AI for an enemy player. I want the AI to move backwards if its ray cast hits the player, however I am having a serious issue. [I will explain below code]
Code;
using UnityEngine;
using System.Collections;
public class NewEnemyAI : MonoBehaviour
{
public GameObject enemy;
public Transform target;
public float movementSpeed = 2f;
private CharacterController enemyCharacterController;
private bool enemyHit;
private Vector3 startPos;
private Vector3 endPos;
private float distance = 7f;
private float lerpTime = 0.3f;
private float currentLerpTime = 0f;
private bool avoid;
private bool updateOn = true;
private bool hitPlayer = false;
// Use this for initialization
void Start ()
{
avoid = false;
}
// Update is called once per frame
void Update ()
{
//raycasting
if (Physics.Raycast(transform.position, transform.forward, 2))
{
startPos = enemy.transform.position;
endPos = enemy.transform.position + Vector3.back * distance;
avoid = true;
}
else
{
avoid = false;
}
if (avoid == true)
{
currentLerpTime += Time.deltaTime;
if (currentLerpTime >= lerpTime)
{
currentLerpTime = lerpTime;
}
float perc = currentLerpTime/lerpTime;
enemy.transform.position = Vector3.Lerp(startPos, endPos, perc);
avoid = false;
}
if (avoid == false)
{
currentLerpTime = 0;
transform.LookAt(target);
transform.Translate(Vector3.forward * Time.deltaTime * movementSpeed);
}
}
}
When the enemy's ray cast hits the player, I set a bool to true, which when that is true, it makes the player move back. However because the player is moving back, the ray cast doesn't hit the player anymore and then this whole process starts again and the enemy just rubber bands because it is jumping from code to code. Is there a way for the code to ignore the ray cast if statement and permanently set the avoid bool to true until told otherwise. thanks! [I am relatively new to C# so please don't criticize my code too much].