I want to spawn an enemy within the navmesh area 180 degrees behind the player

I want to spawn enemies randomly in the navmesh area where the player is behind the layer.

What kind of approach is there?

It will be appreciated if you tell me a reference code etc.

Thank you.

If the player is facing down the transform.forward axis of his object, then you can use the negation of that vector as a guide to where to put the new enemy.

Vector3 enemySpawnPosition = -MyPlayer.transform.forward * DistanceBehindPlayer;

Now that assumes the player “forward” is completely flat, and that the world is flat. This might fail if the player looks up, because then “forward” will be slightly up, and the enemy could spawn under the world.

So you need some more code.

One thing to do is pre-flatten the forward vector:

Vector3 FlattenedForward = MyPlayer.transform.forward;
FlattenedForward.y = 0; // flattened!
FlattenedForward = FlattenedForward.normalized; // make sure it is back to magnitude 1

Then use its negative to put the enemy behind you.

But then if your world isn’t completely flat, you might have more problems with enemies going under ground or falling from the sky.

To address this I generally get the point I want to put the enemy at, then lift it up “some amount” (maybe Vector3.up * 50), and then use a Physics.Raycast to cast down directly from that point to see where I hit the ground, and then use that final RaycastHit object’s “.point” method to put your enemy down.

Hope that sorta gets you going in the right direction!

1 Like

Kurt-Dekker’s post sums it up well, but you’ll also need to use NavMesh.CalculatePath to make sure your spawned AI will have a valid path to the player on the nav mesh: Unity - Scripting API: AI.NavMesh.CalculatePath

2 Likes

Excellent point @GroZZleR … thanks!

I also see the AI.NavMesh.SamplePosition function that might be useful to find a place that actually is on the navmesh.

1 Like

Thankyou! guys!

1 Like