/// <summary> /// When an entity moves around we'll remove it from its old node and add it to its new node (if applicable) /// </summary> /// <param name="moveEvent"></param> private void HandleEntityMove(MoveEvent moveEvent) { // If we've moved to space or the likes then remove us. if (moveEvent.Sender.Deleted || !moveEvent.Sender.TryGetComponent(out IPhysicsComponent physics) || !PathfindingNode.IsRelevant(moveEvent.Sender, physics)) { HandleEntityRemove(moveEvent.Sender); return; } // Memory leak protection until grid parenting confirmed fix / you REALLY need the performance var gridBounds = _mapManager.GetGrid(moveEvent.Sender.Transform.GridID).WorldBounds; if (!gridBounds.Contains(moveEvent.Sender.Transform.WorldPosition)) { HandleEntityRemove(moveEvent.Sender); return; } // If we move from space to a grid we may need to start tracking it. if (!_lastKnownPositions.TryGetValue(moveEvent.Sender, out var oldNode)) { HandleEntityAdd(moveEvent.Sender); return; } var newGridId = moveEvent.NewPosition.GetGridId(_entityManager); if (newGridId == GridId.Invalid) { HandleEntityRemove(moveEvent.Sender); return; } // The pathfinding graph is tile-based so first we'll check if they're on a different tile and if we need to update. // If you get entities bigger than 1 tile wide you'll need some other system so god help you. var newTile = _mapManager.GetGrid(newGridId).GetTileRef(moveEvent.NewPosition); if (oldNode == null || oldNode.TileRef == newTile) { return; } var newNode = GetNode(newTile); _lastKnownPositions[moveEvent.Sender] = newNode; oldNode.RemoveEntity(moveEvent.Sender); newNode.AddEntity(moveEvent.Sender, physics); }
/// <summary> /// Tries to add the entity to the relevant pathfinding node /// </summary> /// The node will filter it to the correct category (if possible) /// <param name="entity"></param> private void HandleEntityAdd(IEntity entity) { if (entity.Deleted || _lastKnownPositions.ContainsKey(entity) || !entity.TryGetComponent(out IPhysicsComponent physics) || !PathfindingNode.IsRelevant(entity, physics)) { return; } var grid = _mapManager.GetGrid(entity.Transform.GridID); var tileRef = grid.GetTileRef(entity.Transform.Coordinates); var chunk = GetChunk(tileRef); var node = chunk.GetNode(tileRef); node.AddEntity(entity, physics); _lastKnownPositions.Add(entity, node); }