Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question OverlapSphereNonAlloc Range issue or is it just me

Discussion in 'Scripting' started by D4rkWells, Aug 19, 2023.

  1. D4rkWells

    D4rkWells

    Joined:
    Nov 20, 2021
    Posts:
    7
    I have this function that I'm testing
    My problem is that even if there no objects inside the radius of "OverlapSphereNonAlloc" (which is 6 units) it still catches an object up until 7 units... I don't know if it is something that I setted up wrong or just something that I'm not aware of... or anything...!?

    Code (CSharp):
    1. public void TransmitAudio()
    2.     {
    3.         var collidersBuffer = new Collider[2]; //Creature(only 1) and Possible Ghost Entities(up to a certain number, TBD)
    4.         var colliderCount = Physics.OverlapSphereNonAlloc(transform.position, _audioTransmitterRadius, collidersBuffer, monsterLayer);
    5.        
    6.         if (colliderCount == 0)
    7.         {
    8.             Debug.Log("No Acceptable Colliders Found");
    9.             return;
    10.         }
    11.        
    12.         for (var i = 0; i < colliderCount; i++)
    13.         {
    14.             var monster = collidersBuffer[i].GetComponent<Creature>();
    15.             Debug.Log(monster, gameObject);
    16.  
    17.             if (monster != null)
    18.             {
    19.                 if (IsObstacleInBetween(monster.transform.position, out var hitCollider))
    20.                 {
    21.                     var obstacleIdentifier = hitCollider.GetComponent<ObstacleIdentifier>();
    22.                     Debug.Log(obstacleIdentifier);
    23.                     if (obstacleIdentifier != null)
    24.                     {
    25.                         var distanceToMonster = Vector3.Distance(transform.position, monster.transform.position);
    26.                         var noiseValue = CalculateForNoiseSuppression(soundMagnitude, obstacleIdentifier.SoundSuppression,
    27.                             distanceToMonster);
    28.                         Debug.Log($"Distance to Monster: {distanceToMonster}");
    29.                         monster.GetAudioInfo(noiseValue);
    30.                     }
    31.                 }
    32.                 else
    33.                 {
    34.                     var distanceToMonster = Vector3.Distance(transform.position, monster.transform.position);
    35.                     var noiseValue =
    36.                         CalculateForNoiseSuppression(soundMagnitude, SoundSuppression.None, distanceToMonster);
    37.                     Debug.Log($"Distance to Monster: {distanceToMonster}");
    38.                     monster.GetAudioInfo(noiseValue);
    39.                 }
    40.             }
    41.             //var distanceToMonster = Vector3.Distance(transform.position, monster.transform.position);
    42.         }
    43.        
    44.         bool IsObstacleInBetween(Vector3 targetPosition, out Collider hitCollider)
    45.         {
    46.             var direction = targetPosition - transform.position;
    47.  
    48.             if (Physics.Raycast(transform.position, direction, out var hit, direction.magnitude))
    49.             {
    50.                 if (hit.collider.GetComponent<Creature>() == null)
    51.                 {
    52.                     hitCollider = hit.collider;
    53.                     return true;
    54.                 }
    55.             }
    56.  
    57.             hitCollider = null;
    58.             return false;
    59.         }
    60.         float CalculateForNoiseSuppression(SoundMagnitude magnitude, SoundSuppression suppression, float distanceToMonster)
    61.         {
    62.             // Calculate the interpolation factor based on the distance
    63.             float interpolationFactor = 1f - Mathf.Clamp01(distanceToMonster / _audioTransmitterRadius);
    64.  
    65.             // Calculate the noise suppression value based on magnitude, suppression, and interpolation factor
    66.             Debug.Log($"Noise based on Distance [from Origin(Noise: {_audioTransmitterRadius}) to Edge of Radius(Noise: {0})] => {(int)magnitude * _noiseSuppression[suppression] * interpolationFactor}");
    67.             return (int)magnitude * _noiseSuppression[suppression] * interpolationFactor;
    68.         }
    69.     }
     
  2. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    are you thinking that the center of said objects is what your range/radius is set to? because even if OverlapSphere catches just one small vert of a collider, it will return it.

    Either that, or distance is bigger than you think, or you're catching the very object that makes the sphere.
     
  3. D4rkWells

    D4rkWells

    Joined:
    Nov 20, 2021
    Posts:
    7
    First, the object where this script is in is an emptyObject at the moment.
    Second, i put both this emptyObject and the target farther then the radius to check it and still found it.
    The radius is based on this:
     _audioTransmitterRadius = (int)soundMagnitude; 

    Set at the start. And the soundMagnitude is this enum:

    public enum SoundMagnitude
    {
    SneakyNoise = 2,
    NormalNoise = 4,
    LoudNoise = 6,
    }

    And I also have this part of the code that checks for the distance between the creature and the object that its producing the sound and it prints a distance greater than
    _audioTransmitterRadius
    :
    Code (CSharp):
    1. if (IsObstacleInBetween(monster.transform.position, out var hitCollider))
    2.                 {
    3.                     var obstacleIdentifier = hitCollider.GetComponent<ObstacleIdentifier>();
    4.                     Debug.Log(obstacleIdentifier);
    5.                     if (obstacleIdentifier != null)
    6.                     {
    7.                         var distanceToMonster = Vector3.Distance(transform.position, monster.transform.position);
    8.                         var noiseValue = CalculateForNoiseSuppression(soundMagnitude, obstacleIdentifier.SoundSuppression,
    9.                             distanceToMonster);
    10.                         Debug.Log($"Distance to Monster: {distanceToMonster}");
    11.                         monster.GetAudioInfo(noiseValue);
    12.                     }
    13.                 }
    14.                 else
    15.                 {
    16.                     var distanceToMonster = Vector3.Distance(transform.position, monster.transform.position);
    17.                     var noiseValue =
    18.                         CalculateForNoiseSuppression(soundMagnitude, SoundSuppression.None, distanceToMonster);
    19.                     Debug.Log($"Distance to Monster: {distanceToMonster}");
    20.                     monster.GetAudioInfo(noiseValue);
    21.                 }
     
  4. D4rkWells

    D4rkWells

    Joined:
    Nov 20, 2021
    Posts:
    7
    for no confusion this is the full script:
    Note:
    soundMagnitude
    is set to
    SoundMagnitude.LoudNoise
    ;
    And
    monsterLayer
    is properly assign in a layer that only the target is.
    Code (CSharp):
    1. using System.Collections.Generic;
    2. using UnityEngine;
    3.  
    4. public enum SoundMagnitude
    5. {
    6.     SneakyNoise = 2,
    7.     NormalNoise = 4,
    8.     LoudNoise   = 6,
    9. }  
    10.  
    11. public enum SoundSuppression
    12. {
    13.     None,
    14.     WoodenWall,
    15.     MetalWall,
    16. }
    17.  
    18. public class AudioManagerTransmitter : MonoBehaviour
    19. {
    20.     [SerializeField] private SoundMagnitude soundMagnitude;
    21.     [SerializeField] private LayerMask monsterLayer;
    22.     private float _audioTransmitterRadius;
    23.  
    24.     private Dictionary<SoundSuppression, float> _noiseSuppression;
    25.  
    26.     private void Start()
    27.     {
    28.         _noiseSuppression = new Dictionary<SoundSuppression, float>()
    29.         {
    30.             { SoundSuppression.None, 1 },
    31.             { SoundSuppression.WoodenWall, .8f },
    32.             { SoundSuppression.MetalWall, .6f },
    33.         };
    34.  
    35.         _audioTransmitterRadius = (int)soundMagnitude; //It works a bit beyond the limit in this variable for some reason...
    36.         Debug.Log($"Noise Radius => {_audioTransmitterRadius}");
    37.     }
    38.  
    39.     private void Update()
    40.     {
    41.         if (Input.GetKeyDown(KeyCode.P))
    42.         {
    43.             TransmitAudio(); //Testing
    44.         }
    45.     }
    46.  
    47.     public void TransmitAudio()
    48.     {
    49.         var collidersBuffer = new Collider[2]; //Creature(only 1) and Possible Ghost Entities(up to a certain number, TBD)
    50.         var colliderCount = Physics.OverlapSphereNonAlloc(transform.position, _audioTransmitterRadius, collidersBuffer, monsterLayer);
    51.        
    52.         if (colliderCount == 0)
    53.         {
    54.             Debug.Log("No Acceptable Colliders Found");
    55.             return;
    56.         }
    57.        
    58.         for (var i = 0; i < colliderCount; i++)
    59.         {
    60.             var monster = collidersBuffer[i].GetComponent<Creature>();
    61.             Debug.Log(monster, gameObject);
    62.  
    63.             if (monster != null)
    64.             {
    65.                 if (IsObstacleInBetween(monster.transform.position, out var hitCollider))
    66.                 {
    67.                     var obstacleIdentifier = hitCollider.GetComponent<ObstacleIdentifier>();
    68.                     Debug.Log(obstacleIdentifier);
    69.                     if (obstacleIdentifier != null)
    70.                     {
    71.                         var distanceToMonster = Vector3.Distance(transform.position, monster.transform.position);
    72.                         var noiseValue = CalculateForNoiseSuppression(soundMagnitude, obstacleIdentifier.SoundSuppression,
    73.                             distanceToMonster);
    74.                         Debug.Log($"Distance to Monster: {distanceToMonster}");
    75.                         monster.GetAudioInfo(noiseValue);
    76.                     }
    77.                 }
    78.                 else
    79.                 {
    80.                     var distanceToMonster = Vector3.Distance(transform.position, monster.transform.position);
    81.                     var noiseValue =
    82.                         CalculateForNoiseSuppression(soundMagnitude, SoundSuppression.None, distanceToMonster);
    83.                     Debug.Log($"Distance to Monster: {distanceToMonster}");
    84.                     monster.GetAudioInfo(noiseValue);
    85.                 }
    86.             }
    87.             //var distanceToMonster = Vector3.Distance(transform.position, monster.transform.position);
    88.         }
    89.        
    90.         bool IsObstacleInBetween(Vector3 targetPosition, out Collider hitCollider)
    91.         {
    92.             var direction = targetPosition - transform.position;
    93.  
    94.             if (Physics.Raycast(transform.position, direction, out var hit, direction.magnitude))
    95.             {
    96.                 if (hit.collider.GetComponent<Creature>() == null)
    97.                 {
    98.                     hitCollider = hit.collider;
    99.                     return true;
    100.                 }
    101.             }
    102.  
    103.             hitCollider = null;
    104.             return false;
    105.         }
    106.         float CalculateForNoiseSuppression(SoundMagnitude magnitude, SoundSuppression suppression, float distanceToMonster)
    107.         {
    108.             // Calculate the interpolation factor based on the distance
    109.             float interpolationFactor = 1f - Mathf.Clamp01(distanceToMonster / _audioTransmitterRadius);
    110.  
    111.             // Calculate the noise suppression value based on magnitude, suppression, and interpolation factor
    112.             Debug.Log($"Noise based on Distance [from Origin(Noise: {_audioTransmitterRadius}) to Edge of Radius(Noise: {0})] => {(int)magnitude * _noiseSuppression[suppression] * interpolationFactor}");
    113.             return (int)magnitude * _noiseSuppression[suppression] * interpolationFactor;
    114.         }
    115.     }
    116. }
    117.  
     
  5. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,917
    Try testing with the simpler OverlapSphere. It's the basic version and will let you see if the overlap part is working. NonAllocate... works the same way, but you have to deal with the more complicated way it returns results.
     
    Bunny83 and spiney199 like this.
  6. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,844
    I also don't see any gizmos in that script. Probably worth using some Gizmos.DrawWireSphere to visualise what the overlap will look like.
     
    Bunny83 and halley like this.
  7. D4rkWells

    D4rkWells

    Joined:
    Nov 20, 2021
    Posts:
    7
    With the Gizmos this is how it looks like!
    Code (CSharp):
    1.  
    2. #if UNITY_EDITOR
    3.     private void OnDrawGizmosSelected()
    4.     {
    5.         Gizmos.color = Color.blue; // Set the color for the wire sphere
    6.         Gizmos.DrawWireSphere(transform.position, (int)soundMagnitude); // Draw the wire sphere
    7.     }
    8. #endif
    9.  
    upload_2023-8-20_0-31-48.png
     
  8. D4rkWells

    D4rkWells

    Joined:
    Nov 20, 2021
    Posts:
    7
    I changed as you said but the result is the same...
     
  9. Qriva

    Qriva

    Joined:
    Jun 30, 2019
    Posts:
    1,108
    Ghosts :)

    Ok, but I can't see any problem, plus just in case I did sanity check in my editor and everything works as expected, so maybe you have second bigger collider on the same object or there is trigger collider or something like that.
    Just to be sure you can try
    Debug.Log(monster, collidersBuffer[i]);
    , but even better would be to try to find closest point on that collider and use gizmo or
    Debug.DrawLine
    to display that line and see what it shows.
    If this does not work, there is only one last thing to do: restart unity :D
     
  10. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    looking at it, I'm remembered of a time I had an issue with int > float or float > int. And seeing your debug log only saying 6 as an int, might be as why. if you gave a float an int value of 6 it should say 6.0... but I can't remember what I did to test..

    man I wish my brain would works sometimes :mad:
     
  11. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    or that.. lol, I did mention it hitting the collider, but never once thought they might be scaled differently.. kudos!