From acea7b2e728787a0d83bbf83c8c1f042d2c32e7e Mon Sep 17 00:00:00 2001 From: chai <215380520@qq.com> Date: Mon, 3 Jun 2024 10:15:45 +0800 Subject: + plugins project --- .../QuadTree/QuadTreeSpace.cs | 76 ++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Plugins/MonoGame.Extended/source/MonoGame.Extended.Collisions/QuadTree/QuadTreeSpace.cs (limited to 'Plugins/MonoGame.Extended/source/MonoGame.Extended.Collisions/QuadTree/QuadTreeSpace.cs') diff --git a/Plugins/MonoGame.Extended/source/MonoGame.Extended.Collisions/QuadTree/QuadTreeSpace.cs b/Plugins/MonoGame.Extended/source/MonoGame.Extended.Collisions/QuadTree/QuadTreeSpace.cs new file mode 100644 index 0000000..3e9625f --- /dev/null +++ b/Plugins/MonoGame.Extended/source/MonoGame.Extended.Collisions/QuadTree/QuadTreeSpace.cs @@ -0,0 +1,76 @@ +using System.Collections.Generic; +using System.Linq; + +namespace MonoGame.Extended.Collisions.QuadTree; + +public class QuadTreeSpace: ISpaceAlgorithm +{ + private readonly QuadTree _collisionTree; + private readonly List _actors = new(); + private readonly Dictionary _targetDataDictionary = new(); + + public QuadTreeSpace(RectangleF boundary) + { + _collisionTree = new QuadTree(boundary); + } + + /// + /// Inserts the target into the collision tree. + /// The target will have its OnCollision called when collisions occur. + /// + /// Target to insert. + public void Insert(ICollisionActor target) + { + if (!_targetDataDictionary.ContainsKey(target)) + { + var data = new QuadtreeData(target); + _targetDataDictionary.Add(target, data); + _collisionTree.Insert(data); + _actors.Add(target); + } + } + + /// + /// Removes the target from the collision tree. + /// + /// Target to remove. + public bool Remove(ICollisionActor target) + { + if (_targetDataDictionary.ContainsKey(target)) + { + var data = _targetDataDictionary[target]; + data.RemoveFromAllParents(); + _targetDataDictionary.Remove(target); + _collisionTree.Shake(); + _actors.Remove(target); + return true; + } + + return false; + } + + /// + /// Restructure a inner collection, if layer is dynamic, because actors can change own position + /// + public void Reset() + { + _collisionTree.ClearAll(); + foreach (var value in _targetDataDictionary.Values) + { + _collisionTree.Insert(value); + } + _collisionTree.Shake(); + } + + /// + /// foreach support + /// + /// + public List.Enumerator GetEnumerator() => _actors.GetEnumerator(); + + /// + public IEnumerable Query(RectangleF boundsBoundingRectangle) + { + return _collisionTree.Query(ref boundsBoundingRectangle).Select(x => x.Target); + } +} -- cgit v1.1-26-g67d0