2D Enemy Pathfinding Issues

Hello -

I hope I’m posting this in the right place.

I’m currently developing a simple top down 2D shooter in the vein of 1942 (except in space. Space makes everything better.). Mostly for funsies, but who knows.

I’m having trouble, however, getting the enemy fighters to path the way I want. I can get them to spawn and fly straight at the player while shooting easily enough, but I don’t want them to kamikaze. I’m trying to figure out a way to get them to fly at the player but at a certain point, break off and fly towards a screen edge.

I’m fairly new at Unity (especially 2D) so I’m having trouble figuring out how to do this well. My first idea was a NavMesh, but evidently that doesn’t work in 2D. If someone could offer a suggestion, I’d appreciate it. (I don’t need the code, just an idea where to start.) Since this is just a learning exercise, I’d prefer not to spend much/any money if it can be helped.

Thank you!

The way i can imagine this is like:

• Spawn the enemy plane.
• Move the enemy plane from the top to the bottom of the screen.
• Let’s say at certain distance passed the enemy plane wants to go at the players direction but not to follow it.So at that point you take only once the position of the player plane and store it in a variable.
• Then you just divert it.

I can suggest using a coroutine in this case like this:

``````    private IEnumerator SpawnEnemyBlindFighter()
{
Vector2 spawnPoint = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height - 10, 0));
Vector2 directionAtDiversion = Vector2.zero;

float leaveScreenPoint = Camera.main.ScreenToWorldPoint(new Vector3(0, 0, 0)).y;
float distanceTraveled = 0;
float distanceToDivertAt = 2f;
float speed = 2f;

GameObject enemyGO = (GameObject)Instantiate(BlindFighterGameObject, spawnPoint, Quaternion.identity);
Transform enemy = enemyGO.transform;

bool directionKept = false;

while (playerPosition.position.y > leaveScreenPoint)
{
distanceTraveled += enemy.position.magnitude;

if (distanceTraveled > distanceToDivertAt)
{
if (!directionKept)
{
directionAtDiversion = enemy.position / enemy.position.magnitude;
directionKept = true;
}

enemy.position += directionAtDiversion * (Time.deltaTime + speed);

}

else
{
enemy.position += (enemy.position.up * -1) * (Time.deltaTime + speed);
}

yield return null;
}

Destroy(enemyGO);
}
``````

You can now start the coroutine (Spawn your fighter) every N seconds and when the enemy gets out of the screen it gets destroyed and the routine finishes.For the player position and the enemy game object I am assuming you have them already cached in your script.If you need further explanations what I am doing you I can explain later because I don’t have time right now.Let me know what happens.