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