SeparationBehavior.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. //-----------------------------------------------------------------------------
  2. // SeparationBehavior.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. /// SeparationBehavior is a Behavior that will make an animal move away from
  13. /// another if it's too close for comfort
  14. /// </summary>
  15. class SeparationBehavior : Behavior
  16. {
  17. public SeparationBehavior(Animal animal)
  18. : base(animal)
  19. {
  20. }
  21. /// <summary>
  22. /// separationBehavior.Update infuences the owning animal to move away from
  23. /// the otherAnimal is it�s too close, in this case if it�s inside
  24. /// AIParameters.separationDistance.
  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 pushDirection = Vector2.Zero;
  32. float weight = aiParams.PerMemberWeight;
  33. if (Animal.ReactionDistance > 0.0f &&
  34. Animal.ReactionDistance <= aiParams.SeparationDistance)
  35. {
  36. //The otherAnimal is too close so we figure out a pushDirection
  37. //vector in the opposite direction of the otherAnimal and then weight
  38. //that reaction based on how close it is vs. our separationDistance
  39. pushDirection = Animal.Location - Animal.ReactionLocation;
  40. Vector2.Normalize(ref pushDirection, out pushDirection);
  41. //push away
  42. weight *= (1 -
  43. (float)Animal.ReactionDistance / aiParams.SeparationDistance);
  44. pushDirection *= weight;
  45. reacted = true;
  46. reaction += pushDirection;
  47. }
  48. }
  49. }
  50. }