Search Unity

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

Discussion in 'Scripting' started by YOAJ1, Jul 2, 2018.

  1. YOAJ1

    YOAJ1

    Joined:
    Jul 17, 2014
    Posts:
    26
    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.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    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.

    Code (csharp):
    1. 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:

    Code (csharp):
    1. Vector3 FlattenedForward = MyPlayer.transform.forward;
    2. FlattenedForward.y = 0; // flattened!
    3. 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!
     
    YOAJ1 likes this.
  3. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    YOAJ1 and Kurt-Dekker like this.
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    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.
     
    YOAJ1 likes this.
  5. YOAJ1

    YOAJ1

    Joined:
    Jul 17, 2014
    Posts:
    26
    Thankyou! guys!
     
    Kurt-Dekker likes this.