Blipples

ConeDetection

May 11th, 2024
16
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. public bool Detect(Transform detector, CountdownTimer timer, int numberOfRays = 10)
  2. {
  3. //If the timer is running, the NPC is already aware of the player
  4. if (timer.IsRunning)
  5. {
  6. return false;
  7. }
  8.  
  9. //Get the movement direction
  10. Vector2 movementDirection = detector.gameObject.GetComponent<NPC>().MovementController.Destination - (Vector2)detector.position;
  11.  
  12. // If the NPC has reached its destination, keep the last valid movement direction
  13. // This is to prevent the raycast from flipping 180 degrees when the NPC stops moving
  14. if (movementDirection.sqrMagnitude < 0.01f)
  15. {
  16. movementDirection = lastMovementDirection;
  17. }
  18. else
  19. {
  20. lastMovementDirection = movementDirection;
  21. }
  22.  
  23. // Get the angle between the movement direction and the forward vector of the detector
  24. var angleToPlayer = Vector3.Angle(movementDirection, detector.forward);
  25.  
  26. // Calculate the start and end angles for the cone
  27. float startAngle = -detectionAngle / 2f;
  28. float endAngle = detectionAngle / 2f;
  29.  
  30. // Calculate the step size for each ray
  31. float stepSize = (endAngle - startAngle) / (numberOfRays - 1);
  32.  
  33. // Get the angle of the movement vector in radians
  34. float angleMovement = Mathf.Atan2(movementDirection.y, movementDirection.x);
  35.  
  36. LayerMask layerMask = LayerMask.GetMask("Player");
  37.  
  38. for (int i = 0; i < numberOfRays; i++)
  39. {
  40. // Calculate the angle for this ray
  41. float angle = startAngle + stepSize * i + angleMovement;
  42.  
  43. // Calculate the direction for this ray
  44. Vector2 direction = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));
  45.  
  46. // Cast the ray
  47. RaycastHit2D hit = Physics2D.Raycast(detector.position, direction, detectionRadius, layerMask);
  48.  
  49. // Draw the ray in the Scene view
  50. Debug.DrawRay(detector.position, direction * detectionRadius, Color.red);
  51.  
  52. // If the ray hit a player, return true
  53. if (hit.collider != null && hit.collider.CompareTag("Player"))
  54. {
  55. player = hit.collider.transform;
  56.  
  57. // Restart the timer to check again
  58. timer.Start();
  59. return true;
  60. }
  61. }
  62.  
  63. return false;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment