Search Unity

Spatial Hash for particle system broken

Discussion in 'Scripting' started by KEELAN, Dec 22, 2014.

  1. KEELAN

    KEELAN

    Joined:
    Oct 26, 2013
    Posts:
    51
    Hi all
    I am making a spatial hash with for a particle system. One of the things required is to find neighboring particles, which is were the error is I believe. Anyway, it seems broken and not retriving the right neighbors and I cant really tell why. I would really appreciate any help here

    Kind Regards

    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System.Linq;

    5. public class SpatialHash {

    6. Dictionary<int,List<Particle>> hash;//= new Dictionary<List<Particle>,int>();
    7. public float cellSize;
    8. public int max;

    9. public SpatialHash(float cSize,int m)
    10. {
    11. hash = new Dictionary<int,List<Particle>>();
    12. cellSize = cSize;
    13. max = m;
    14. }

    15. public void AddParticleToHash(Particle nParticle, int key)
    16. {
    17. if(hash.ContainsKey(key))
    18. hash[key].Add(nParticle);
    19. else
    20. {
    21. hash.Add(key,new List<Particle>());
    22. hash[key].Add(nParticle);
    23. }
    24. }
    25. public void ClearGrid()
    26. {
    27. hash.Clear();
    28. }
    29. public int GetKey(Vector2 position)
    30. {
    31. return (int)(position.x/cellSize)*max +(int)(position.y/cellSize);
    32. }
    33. public List<Particle> getNeighbors(int key , int searchDistance , int capacity)
    34. {
    35. int x = (key/max);
    36. int y = key - x*max;

    37. List<Particle> temp = new List<Particle>();

    38. for(int i = x - searchDistance; i <= x + searchDistance ;i++)
    39. {
    40. for(int j = y - searchDistance; j <= y + searchDistance ;j++)
    41. {
    42. int keyTemp = (i)*max +(j);
    43. if(hash.ContainsKey(keyTemp))
    44. {
    45. temp.AddRange(hash[keyTemp]);
    46. }
    47. }
    48. }
    49. return temp;
    50. }

    51. }