Vector3Helper.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //-----------------------------------------------------------------------------
  2. // Vector3Helper.cs
  3. //
  4. // Microsoft XNA Community Game Platform
  5. // Copyright (C) Microsoft Corporation. All rights reserved.
  6. //-----------------------------------------------------------------------------
  7. using Microsoft.Xna.Framework;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Text;
  11. using System.IO;
  12. namespace RacingGame.Helpers
  13. {
  14. /// <summary>
  15. /// Vector 3 helper
  16. /// </summary>
  17. class Vector3Helper
  18. {
  19. /// <summary>
  20. /// Private constructor to prevent instantiation.
  21. /// </summary>
  22. private Vector3Helper()
  23. {
  24. }
  25. /// <summary>
  26. /// Return angle between two vectors. Used for visbility testing and
  27. /// for checking angles between vectors for the road sign generation.
  28. /// </summary>
  29. /// <param name="vec1">Vector 1</param>
  30. /// <param name="vec2">Vector 2</param>
  31. /// <returns>Float</returns>
  32. public static float GetAngleBetweenVectors(Vector3 vec1, Vector3 vec2)
  33. {
  34. // See http://en.wikipedia.org/wiki/Vector_(spatial)
  35. // for help and check out the Dot Product section ^^
  36. // Both vectors are normalized so we can save deviding through the
  37. // lengths.
  38. return (float)Math.Acos(Vector3.Dot(vec1, vec2));
  39. }
  40. /// <summary>
  41. /// Distance from our point to the line described by linePos1 and linePos2.
  42. /// </summary>
  43. /// <param name="point">Point</param>
  44. /// <param name="linePos1">Line position 1</param>
  45. /// <param name="linePos2">Line position 2</param>
  46. /// <returns>Float</returns>
  47. public static float DistanceToLine(Vector3 point,
  48. Vector3 linePos1, Vector3 linePos2)
  49. {
  50. // For help check out this article:
  51. // http://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html
  52. Vector3 lineVec = linePos2 - linePos1;
  53. Vector3 pointVec = linePos1 - point;
  54. return Vector3.Cross(lineVec, pointVec).Length() / lineVec.Length();
  55. }
  56. /// <summary>
  57. /// Signed distance to plane
  58. /// </summary>
  59. /// <param name="point">Point</param>
  60. /// <param name="planePosition">Plane position</param>
  61. /// <param name="planeNormal">Plane normal</param>
  62. /// <returns>Float</returns>
  63. public static float SignedDistanceToPlane(Vector3 point,
  64. Vector3 planePosition, Vector3 planeNormal)
  65. {
  66. Vector3 pointVec = planePosition - point;
  67. return Vector3.Dot(planeNormal, pointVec);
  68. }
  69. }
  70. }