PageRenderTime 94ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/Samples/CarGame2D/Track.cs

#
C# | 57 lines | 48 code | 6 blank | 3 comment | 4 complexity | 7b2c448bf6ab8c7961798c69c45082dd MD5 | raw file
Possible License(s): Apache-2.0
  1. using DeltaEngine.Content;
  2. using DeltaEngine.Datatypes;
  3. using DeltaEngine.Rendering2D;
  4. namespace CarGame2D
  5. {
  6. /// <summary>
  7. /// Track class for the game, handles painting and helps with collision checking.
  8. /// </summary>
  9. public class Track : Entity2D
  10. {
  11. public Track(Vector2D[] positions)
  12. {
  13. Positions = positions;
  14. Material = new Material(ShaderFlags.Position2DTextured, "TrackImage");
  15. OnDraw<TrackRenderer>();
  16. CenterAllPositions(positions);
  17. TrackStart = positions[0];
  18. CalculateInnerAndOuterBounds(positions);
  19. }
  20. public Vector2D[] Positions { get; private set; }
  21. public Material Material { get; private set; }
  22. private static void CenterAllPositions(Vector2D[] positions)
  23. {
  24. Vector2D center = positions[0];
  25. for (int index = 1; index < positions.Length; index++)
  26. center += positions[index];
  27. center /= positions.Length;
  28. Vector2D offset = new Vector2D(0.5f, 0.49f) - center;
  29. for (int index = 0; index < positions.Length; index++)
  30. positions[index] += offset;
  31. }
  32. public Vector2D TrackStart { get; private set; }
  33. private void CalculateInnerAndOuterBounds(Vector2D[] positions)
  34. {
  35. TrackInnerBounds = new Vector2D[positions.Length];
  36. TrackOuterBounds = new Vector2D[positions.Length];
  37. for (int index = 0; index < Positions.Length; index++)
  38. {
  39. var previousPos = Positions[index - 1 == -1 ? Positions.Length - 1 : index - 1];
  40. var nextPos = Positions[(index + 1) % Positions.Length];
  41. var dir = Vector2D.Normalize(nextPos - previousPos);
  42. var normal = Vector2D.Normalize(dir.Rotate(90));
  43. TrackOuterBounds[index] = Positions[index] - normal * TrackWidth * 0.5f;
  44. TrackInnerBounds[index] = Positions[index] + normal * TrackWidth * 0.5f;
  45. }
  46. }
  47. public Vector2D[] TrackInnerBounds { get; private set; }
  48. public Vector2D[] TrackOuterBounds { get; private set; }
  49. public const float TrackWidth = 0.12f;
  50. }
  51. }