Currently I’m working on AI enemies in my project and I ran into a problem that I can’t solve,
In the following script, I made the AI run after the player if he see’s him, or he gets hit by the player,
problem is that the enemy runs away from me, I run towards the enemy and he flees back, the AI enemy can’t be in a distance less then 12 units from me. dunno what I made wrong, but it’s kinda weird.
we need to see the MoveTowardsPlayer() function, or you script is reverting to the EnemyCalmState, and that might be move away from player
my code notes
if (!Health.isDead() && (HaveSeenPlayer() || gotHit))
{
if (Distance > 4f) // if the player is to far away then move closer
{
MoveTowardsPlayer(); // move closer
}else
{
Attack(); // i'm close enough so attach the player
}
}else //i'm dead, or i have not seen the player or have not gotten hit by the player
{
EnemyCalmState(); // do the calm state, ie, idle, patrol....
}
void EnemyCalmState()
{
Vector2 newPosToWalk = new Vector2(newXPos, transform.position.y); // Vector for the new position
if (!newPositionOnce) {
newXPos = Random.Range(SpawnedPosOnXaxis - 5, SpawnedPosOnXaxis + 5);
newPositionOnce = true;
} // A random point that the enemy can go to
if ((int)transform.position.x != (int)newXPos) // if the enemy hasn't reached the new position yet
{
rb.AddForce((newPosToWalk - (Vector2)transform.position) * enemyWalkSpeed);
EnemyAnimationController.Walk();
ChangeEnemyDirection(newXPos);
}
else // if the enemy has reached the new position, it will rest 2 seconds, and then timer will reset, and also one time bool will renabled for a new X position.
{
EnemyAnimationController.Idle();
Timer += Time.deltaTime;
if (Timer > 2)
{
newPositionOnce = false;
Timer = 0;
}
}
}
my 2 cents while someone else is helping you:
If you need only compare a distance as < or > , instead of Distance, you can use (target.position - transform.position).sqrMagnitude
then check if that value is less than or greater than your checkedDistance * checkedDistance