2016-09-19 7 views
0

私は自分のゲームアルゴリズムで空間ハッシングを実装しました。空間ハッシングで隣人の四角形を見つけるには?

現在の四角形の他のオブジェクトを見ることができますが、それは現在の四角の端にあり、他の四角形の最も近い点を見ることはできません。

隣の四角(1,2,3)のオブジェクトを取得したい 最も近い四角形の取得方法は?

using System.Linq; 
using UnityEngine; 
using System.Collections.Generic; 

public class SpatialHash<T> 
{ 
    private Dictionary<int, List<T>> dict; 
    private Dictionary<T, int> objects; 
    private int cellSize; 

    public SpatialHash(int cellSize) 
    { 
     this.cellSize = cellSize; 
     dict = new Dictionary<int, List<T>>(); 
     objects = new Dictionary<T, int>(); 
    } 

    public void Insert(Vector3 vector, T obj) 
    { 
     var key = Key(vector); 
     if (dict.ContainsKey(key)) 
     { 
      dict[key].Add(obj); 
     } 
     else 
     { 
      dict[key] = new List<T> { obj }; 
     } 
     objects[obj] = key; 
    } 

    public void UpdatePosition(Vector3 vector, T obj) 
    { 
     if (objects.ContainsKey(obj)) 
     { 
      dict[objects[obj]].Remove(obj); 
     } 
     Insert(vector, obj); 
    } 

    public List<T> QueryPosition(Vector3 vector) 
    { 
     var key = Key(vector); 
     return dict.ContainsKey(key) ? dict[key] : new List<T>(); 
    } 

    public bool ContainsKey(Vector3 vector) 
    { 
     return dict.ContainsKey(Key(vector)); 
    } 

    public void Clear() 
    { 
     var keys = dict.Keys.ToArray(); 
     for (var i = 0; i < keys.Length; i++) 
      dict[keys[i]].Clear(); 
     objects.Clear(); 
    } 

    public void Reset() 
    { 
     dict.Clear(); 
     objects.Clear(); 
    } 

    private const int BIG_ENOUGH_INT = 16 * 1024; 
    private const double BIG_ENOUGH_FLOOR = BIG_ENOUGH_INT + 0.0000; 

    private static int FastFloor(float f) 
    { 
     return (int)(f + BIG_ENOUGH_FLOOR) - BIG_ENOUGH_INT; 
    } 

    private int Key(Vector3 v) 
    { 
     return ((FastFloor(v.x/cellSize) * 73856093)^
       (FastFloor(v.y/cellSize) * 19349663)^
       (FastFloor(v.z/cellSize) * 83492791)); 
    } 
} 

picture

+0

mm ..コードはどこですか? – raven

答えて

0

あなたはクラスに新しいメソッドとしてこれを追加することができます:私はプライベートメソッドにQueryPositionを変更し、APIを維持するために、パブリックとしてこれだけを持っているでしょう

//get the list of objects that are in the cell that is specified cells away 
//in each direction from the given location 
public List<T> QueryRelativePosition(Vector3 vector, 
          int cellsLeft, int cellsUp, int cellsForward) 
{ 
    float posLeft = ((float) cellsLeft)/cellSize; 
    float posUp = ((float) cellsUp)/cellSize; 
    float posForward = ((float) cellsForward)/cellSize; 
    return QueryPosition(vector + (posLeft * Vector3.left) + 
            (posUp * Vector3.up) + 
            (posForward * Vector3.forward)); 
} 

小さくて扱いやすいですが、あなたはそれらを公開することができます。

3つのコンポーネントをすべて使用しているので、この方法では3つの軸すべてをセル単位で移動できます(これで、隣接するセルを簡単に検査できます)。それを使って遠方の細胞も検査する)。

+0

返信ありがとうございます。私はここで私の問題のためのよりよい解決策を見つけましたhttp://gameprogrammingpatterns.com/spatial-partition.html#design-decisions、それにもかかわらず、最終的に私はquadtreeを使用することにしました。さまざまなサイズのオブジェクトやそれらと操作するオブジェクトに適しています。 –

関連する問題