SeparationBehavior.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // SeparationBehavior.cs
  4. //
  5. // Microsoft XNA Community Game Platform
  6. // Copyright (C) Microsoft Corporation. All rights reserved.
  7. //-----------------------------------------------------------------------------
  8. #endregion
  9. #region Using Statements
  10. using System;
  11. using Microsoft.Xna.Framework;
  12. #endregion
  13. namespace Flocking
  14. {
  15. /// <summary>
  16. /// SeparationBehavior is a Behavior that will make an animal move away from
  17. /// another if it's too close for comfort
  18. /// </summary>
  19. class SeparationBehavior : Behavior
  20. {
  21. #region Initialization
  22. public SeparationBehavior(Animal animal)
  23. : base(animal)
  24. {
  25. }
  26. #endregion
  27. #region Update
  28. /// <summary>
  29. /// separationBehavior.Update infuences the owning animal to move away from
  30. /// the otherAnimal is it’s too close, in this case if it’s inside
  31. /// AIParameters.separationDistance.
  32. /// </summary>
  33. /// <param name="otherAnimal">the Animal to react to</param>
  34. /// <param name="aiParams">the Behaviors' parameters</param>
  35. public override void Update(Animal otherAnimal, AIParameters aiParams)
  36. {
  37. base.ResetReaction();
  38. Vector2 pushDirection = Vector2.Zero;
  39. float weight = aiParams.PerMemberWeight;
  40. if (Animal.ReactionDistance > 0.0f &&
  41. Animal.ReactionDistance <= aiParams.SeparationDistance)
  42. {
  43. //The otherAnimal is too close so we figure out a pushDirection
  44. //vector in the opposite direction of the otherAnimal and then weight
  45. //that reaction based on how close it is vs. our separationDistance
  46. pushDirection = Animal.Location - Animal.ReactionLocation;
  47. Vector2.Normalize(ref pushDirection, out pushDirection);
  48. //push away
  49. weight *= (1 -
  50. (float)Animal.ReactionDistance / aiParams.SeparationDistance);
  51. pushDirection *= weight;
  52. reacted = true;
  53. reaction += pushDirection;
  54. }
  55. }
  56. #endregion
  57. }
  58. }