Search Unity

Question Getting a random point on navmesh within camera view

Discussion in 'Navigation' started by Neith, Dec 27, 2022.

  1. Neith

    Neith

    Joined:
    Feb 11, 2015
    Posts:
    6
    I'm looking for how to get a random point on my navmesh that is also within what the camera can see. Any help would be appreciated!
     
  2. Neith

    Neith

    Joined:
    Feb 11, 2015
    Posts:
    6
    Nevermind... ChatGPT helped me figure it out :D

    something like this...
    Code (CSharp):
    1.  
    2. public static bool RandomPointOnNavMeshInsideCameraView(Camera camera, Vector3 center, float range, out Vector3 result, int areaMask = UnityEngine.AI.NavMesh.AllAreas, int maxIterations = 1000)
    3.     {
    4.         for (int i = 0; i < maxIterations; i++)
    5.         {
    6.             // Generate a random position within the range
    7.             Vector3 randomPosition = center + UnityEngine.Random.insideUnitSphere * range;
    8.  
    9.             // Sample a point on the navmesh at the random position
    10.             UnityEngine.AI.NavMeshHit hit;
    11.             if (UnityEngine.AI.NavMesh.SamplePosition(randomPosition, out hit, range, areaMask))
    12.             {
    13.                 // Check if the point is within the camera's view
    14.                 Vector3 viewportPoint = camera.WorldToViewportPoint(hit.position);
    15.                 if (viewportPoint.z > 0 && viewportPoint.x > 0 && viewportPoint.x < 1 && viewportPoint.y > 0 && viewportPoint.y < 1)
    16.                 {
    17.                     result = hit.position;
    18.                     return true;
    19.                 }
    20.             }
    21.         }
    22.  
    23.         result = center;
    24.         return false;
    25.     }
    26.  
     
    Last edited: Dec 27, 2022
    Dreamy_T likes this.
  3. Dreamy_T

    Dreamy_T

    Joined:
    Dec 23, 2015
    Posts:
    11

    Thank you for your self answering! I could write a modified code from this. which is 'A position out side of the Camera view' for enemy spawn position! In my case, Random.onUnitSphere was better. (because i needed outside of viewport somewhere)