Help with enemy AI

Hi,

I’m having some trouble programming the AI of an enemy in my game. The enemy I’m making is supposed to ram the player and try to get the player off the edge of the map. So far, I have programmed the enemy to follow the player around. I want to program the enemy to actually start backing up and ramming the player once it gets close enough, instead of just pushing against the player when it reaches you.

Here is (a part of) my code so far:

void FixedUpdate () {

		if (transform.position.y < -5 || player.transform.position.y < -50) {

			WaveSpawner.enemiesAlive--;
			Destroy (gameObject);
		}
			
		inactive = transform.position.y < 0.5;

		if (!inactive) {

			if (Vector3.Distance (transform.position, player.transform.position) > 2) {

				rb.AddForce ((player.transform.position - transform.position).normalized * speed);

			} else if (Vector3.Distance (transform.position, player.transform.position) < 2) {

				rb.AddForce (-(player.transform.position - transform.position).normalized * (speed / 3));
			} 

		}

	}

This doesn’t work because whenever the enemy starts to ram the player, the script that tells the enemy to back up starts coming in and stops the enemy from ramming the player.

I tried many other possible solutions to the problem, but none of them worked.

Is there any way to make it work?

*Note: I know that the code is messy, I just want to make sure it works first before fixing it

Try to make a script that’s not based on distance, but based on collision and time!

float collisionTime;

OnCollisionEnter (Collider other)
{
    collisionTime = Time.time;
}

Update ()
{
    if (Time.time > collisionTime + 2)
    {
        //Go Forwards
    }
    else
    {
        //Reverse
    }
}

I’ve done something exactly like this once, although I took a different approach where I would just add a strong backwards force to them if they got stuck on a wall/player for too long. It also helps if you add a bouncy PhysicsMaterial to the enemies, so they automatically bounce off a bit.