Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public bool Detect(Transform detector, CountdownTimer timer, int numberOfRays = 10)
- {
- //If the timer is running, the NPC is already aware of the player
- if (timer.IsRunning)
- {
- return false;
- }
- //Get the movement direction
- Vector2 movementDirection = detector.gameObject.GetComponent<NPC>().MovementController.Destination - (Vector2)detector.position;
- // If the NPC has reached its destination, keep the last valid movement direction
- // This is to prevent the raycast from flipping 180 degrees when the NPC stops moving
- if (movementDirection.sqrMagnitude < 0.01f)
- {
- movementDirection = lastMovementDirection;
- }
- else
- {
- lastMovementDirection = movementDirection;
- }
- // Get the angle between the movement direction and the forward vector of the detector
- var angleToPlayer = Vector3.Angle(movementDirection, detector.forward);
- // Calculate the start and end angles for the cone
- float startAngle = -detectionAngle / 2f;
- float endAngle = detectionAngle / 2f;
- // Calculate the step size for each ray
- float stepSize = (endAngle - startAngle) / (numberOfRays - 1);
- // Get the angle of the movement vector in radians
- float angleMovement = Mathf.Atan2(movementDirection.y, movementDirection.x);
- LayerMask layerMask = LayerMask.GetMask("Player");
- for (int i = 0; i < numberOfRays; i++)
- {
- // Calculate the angle for this ray
- float angle = startAngle + stepSize * i + angleMovement;
- // Calculate the direction for this ray
- Vector2 direction = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));
- // Cast the ray
- RaycastHit2D hit = Physics2D.Raycast(detector.position, direction, detectionRadius, layerMask);
- // Draw the ray in the Scene view
- Debug.DrawRay(detector.position, direction * detectionRadius, Color.red);
- // If the ray hit a player, return true
- if (hit.collider != null && hit.collider.CompareTag("Player"))
- {
- player = hit.collider.transform;
- // Restart the timer to check again
- timer.Start();
- return true;
- }
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment