Advertisement
kadyr

Untitled

Oct 10th, 2021
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.AI;
  6. using Random = UnityEngine.Random;
  7.  
  8. public class GetNavmesh : MonoBehaviour
  9. {
  10. void DrawCircle(Vector3 center, float radius, Color color)
  11. {
  12. Vector3 prevPos = center + new Vector3(radius, 0, 0);
  13. for (int i = 0; i < 30; i++)
  14. {
  15. float angle = (float)(i + 1) / 30.0f * Mathf.PI * 2.0f;
  16. Vector3 newPos = center + new Vector3(Mathf.Cos(angle) * radius, 0, Mathf.Sin(angle) * radius);
  17. Debug.DrawLine(prevPos, newPos, color);
  18. prevPos = newPos;
  19. }
  20. }
  21.  
  22. public float distanceToNewPoint = 25f; //how far away is the new point
  23.  
  24. private NavMeshAgent agent;
  25.  
  26. private void Start()
  27. {
  28. agent = GetComponent<NavMeshAgent>();
  29. StartCoroutine(FindNavmesh());
  30. }
  31.  
  32. private IEnumerator FindNavmesh()
  33. {
  34. NavMeshPath path = new NavMeshPath();
  35. Vector3 newDest;
  36. do
  37. {
  38. //random vector3
  39. Vector3 randomDirection = new Vector3(Random.value, Random.value, Random.value);
  40. //set the magnitude of the vector3 (this could be randomized too if you want)
  41. randomDirection *= distanceToNewPoint;
  42. //randomly pick a negative value for the x or z
  43. if (Random.Range(0, 2) == 0) randomDirection.x *= -1;
  44. if (Random.Range(0, 2) == 0) randomDirection.z *= -1;
  45.  
  46. //add the random vector to the current position
  47. Vector3 v = transform.position + randomDirection;
  48.  
  49. //determine the y value by looking at the terrain height
  50. float y;
  51. y = Terrain.activeTerrain.SampleHeight(v) + Terrain.activeTerrain.transform.position.y;
  52.  
  53. newDest = new Vector3(v.x, y, v.z);
  54.  
  55. //calculate the path
  56. agent.CalculatePath(newDest, path);
  57. Debug.Log(path.status);
  58. yield return null;
  59. } while (path.status != NavMeshPathStatus.PathComplete);
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement