CohesionBehavior.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // CohesionBehavior.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. /// CohesionBehavior is a Behavior that makes an animal move towards another
  17. /// if it's not already too close
  18. /// </summary>
  19. class CohesionBehavior : Behavior
  20. {
  21. #region Initialization
  22. public CohesionBehavior(Animal animal)
  23. : base(animal)
  24. {
  25. }
  26. #endregion
  27. #region Update
  28. /// <summary>
  29. /// CohesionBehavior.Update infuences the owning animal to move towards the
  30. /// otherAnimal that it sees as long as it isn’t too close, in this case
  31. /// that means inside the separationDist in the passed in AIParameters.
  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 pullDirection = Vector2.Zero;
  39. float weight = aiParams.PerMemberWeight;
  40. //if the otherAnimal is too close we dont' want to fly any
  41. //closer to it
  42. if (Animal.ReactionDistance > 0.0f
  43. && Animal.ReactionDistance > aiParams.SeparationDistance)
  44. {
  45. //We want to make the animal move closer the the otherAnimal so we
  46. //create a pullDirection vector pointing to the otherAnimal bird and
  47. //weigh it based on how close the otherAnimal is relative to the
  48. //AIParameters.separationDistance.
  49. pullDirection = -(Animal.Location - Animal.ReactionLocation);
  50. Vector2.Normalize(ref pullDirection, out pullDirection);
  51. weight *= (float)Math.Pow((double)
  52. (Animal.ReactionDistance - aiParams.SeparationDistance) /
  53. (aiParams.DetectionDistance - aiParams.SeparationDistance), 2);
  54. pullDirection *= weight;
  55. reacted = true;
  56. reaction = pullDirection;
  57. }
  58. }
  59. #endregion
  60. }
  61. }