private void ObjectsInRectSearch(FloatRect rect, ICollection <T> results) { var idx = FindBucketIndex(rect.Center()); var range = (rect.Center() - rect.Min()).Length(); var bucketRangeX = (int)(range / m_BucketWidth) + 1; if (bucketRangeX < 0) { bucketRangeX = m_NumBucketsWidth / 2; } var bucketRangeY = (int)(range / m_BucketHeight) + 1; if (bucketRangeY < 0) { bucketRangeY = m_NumBucketsHeight / 2; } for (int i = -bucketRangeX; i <= bucketRangeX; i++) { for (int j = -bucketRangeY; j <= bucketRangeY; j++) { var nextIdx = idx + (i + (j * m_NumBucketsWidth)); // If index is out of range if (nextIdx < 0 || nextIdx >= m_Buckets.Length) { continue; } if (m_Buckets[nextIdx] == null) { continue; } var bucket = m_Buckets[nextIdx]; for (int n = 0; n < bucket.Count; n++) { if (!rect.Contains(bucket[n].Position.X, bucket[n].Position.Y)) { continue; } results.Add(bucket[n]); } } } }
private void RefreshTest() { foreach (var testObject in m_TestObjects) { var pos = GetRandomPos(); testObject.Key.Position = pos; } m_MainTestObject.Position = m_Bounds.Center(); }
public QuadTreeDemo() { m_Bounds = new FloatRect(new Vector2f(0, 0), (Vector2f)Game.Window.Size); for (var i = 0; i < m_NumCircles; i++) { var pos = GetRandomPos(); m_TestObjects.Add(new CircleShape(2f) { FillColor = Color.Blue, Position = pos }, RandomVelocity()); } m_MainTestObject = m_TestObjects.First().Key; m_MainTestObject.Position = m_Bounds.Center(); m_Tree = new QuadTree <Transformable>(m_Bounds); foreach (var obj in m_TestObjects.Select(kvp => kvp.Key).Cast <Transformable>().ToList()) { m_Tree.Add(obj); } Game.Window.KeyPressed += (sender, args) => { if (args.Code == Keyboard.Key.Space) { m_ShowCircles = !m_ShowCircles; } }; Game.Window.MouseWheelMoved += (sender, args) => { m_NumCircles += args.Delta * 3; if (m_NumCircles < 10) { m_NumCircles = 10; } Console.WriteLine(m_NumCircles + " " + m_TestObjects.Count); }; }