CohesionBehavior.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. //-----------------------------------------------------------------------------
  2. // CohesionBehavior.cs
  3. //
  4. // Microsoft XNA Community Game Platform
  5. // Copyright (C) Microsoft Corporation. All rights reserved.
  6. //-----------------------------------------------------------------------------
  7. using System;
  8. using Microsoft.Xna.Framework;
  9. namespace Flocking
  10. {
  11. /// <summary>
  12. /// CohesionBehavior is a Behavior that makes an animal move towards another
  13. /// if it's not already too close
  14. /// </summary>
  15. class CohesionBehavior : Behavior
  16. {
  17. public CohesionBehavior(Animal animal)
  18. : base(animal)
  19. {
  20. }
  21. /// <summary>
  22. /// CohesionBehavior.Update infuences the owning animal to move towards the
  23. /// otherAnimal that it sees as long as it isn�t too close, in this case
  24. /// that means inside the separationDist in the passed in AIParameters.
  25. /// </summary>
  26. /// <param name="otherAnimal">the Animal to react to</param>
  27. /// <param name="aiParams">the Behaviors' parameters</param>
  28. public override void Update(Animal otherAnimal, AIParameters aiParams)
  29. {
  30. base.ResetReaction();
  31. Vector2 pullDirection = Vector2.Zero;
  32. float weight = aiParams.PerMemberWeight;
  33. //if the otherAnimal is too close we dont' want to fly any
  34. //closer to it
  35. if (Animal.ReactionDistance > 0.0f
  36. && Animal.ReactionDistance > aiParams.SeparationDistance)
  37. {
  38. //We want to make the animal move closer the the otherAnimal so we
  39. //create a pullDirection vector pointing to the otherAnimal bird and
  40. //weigh it based on how close the otherAnimal is relative to the
  41. //AIParameters.separationDistance.
  42. pullDirection = -(Animal.Location - Animal.ReactionLocation);
  43. Vector2.Normalize(ref pullDirection, out pullDirection);
  44. weight *= (float)Math.Pow((double)
  45. (Animal.ReactionDistance - aiParams.SeparationDistance) /
  46. (aiParams.DetectionDistance - aiParams.SeparationDistance), 2);
  47. pullDirection *= weight;
  48. reacted = true;
  49. reaction = pullDirection;
  50. }
  51. }
  52. }
  53. }