1
0

NearbyEntities.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using Content.Shared.Whitelist;
  2. namespace Content.Shared.Random.Rules;
  3. /// <summary>
  4. /// Checks for entities matching the whitelist in range.
  5. /// This is more expensive than <see cref="NearbyComponentsRule"/> so prefer that!
  6. /// </summary>
  7. public sealed partial class NearbyEntitiesRule : RulesRule
  8. {
  9. /// <summary>
  10. /// How many of the entity need to be nearby.
  11. /// </summary>
  12. [DataField]
  13. public int Count = 1;
  14. [DataField(required: true)]
  15. public EntityWhitelist Whitelist = new();
  16. [DataField]
  17. public float Range = 10f;
  18. public override bool Check(EntityManager entManager, EntityUid uid)
  19. {
  20. if (!entManager.TryGetComponent(uid, out TransformComponent? xform) ||
  21. xform.MapUid == null)
  22. {
  23. return false;
  24. }
  25. var transform = entManager.System<SharedTransformSystem>();
  26. var lookup = entManager.System<EntityLookupSystem>();
  27. var whitelistSystem = entManager.System<EntityWhitelistSystem>();
  28. var found = false;
  29. var worldPos = transform.GetWorldPosition(xform);
  30. var count = 0;
  31. foreach (var ent in lookup.GetEntitiesInRange(xform.MapID, worldPos, Range))
  32. {
  33. if (whitelistSystem.IsWhitelistFail(Whitelist, ent))
  34. continue;
  35. count++;
  36. if (count < Count)
  37. continue;
  38. found = true;
  39. break;
  40. }
  41. if (!found)
  42. return Inverted;
  43. return !Inverted;
  44. }
  45. }