PageRenderTime 122ms CodeModel.GetById 60ms app.highlight 5ms RepoModel.GetById 56ms app.codeStats 0ms

/Samples/CarGame2D/Track.cs

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