PageRenderTime 87ms CodeModel.GetById 30ms app.highlight 30ms RepoModel.GetById 20ms app.codeStats 0ms

/Samples/Breakout/Paddle.cs

#
C# | 81 lines | 70 code | 8 blank | 3 comment | 1 complexity | bbfef1fac52ebd0a7e382ff90d7864e9 MD5 | raw file
 1using System.Collections.Generic;
 2using DeltaEngine.Commands;
 3using DeltaEngine.Content;
 4using DeltaEngine.Datatypes;
 5using DeltaEngine.Entities;
 6using DeltaEngine.Extensions;
 7using DeltaEngine.Input;
 8using DeltaEngine.Rendering2D;
 9
10namespace Breakout
11{
12	/// <summary>
13	/// Holds the paddle position
14	/// </summary>
15	public class Paddle : Sprite
16	{
17		public Paddle()
18			: base(new Material(ShaderFlags.Position2DColoredTextured, "Paddle"), Rectangle.One)
19		{
20			RegisterInputCommands();
21			Start<RunPaddle>();
22			RenderLayer = 5;
23		}
24
25		private void RegisterInputCommands()
26		{
27			RegisterButtonCommands();
28			new Command(DoMovementByMouseClick).Add(
29				new MouseButtonTrigger(MouseButton.Left, State.Pressed));
30		}
31
32		private void DoMovementByMouseClick(Vector2D clickPosition)
33		{
34			var moveDistAbsolute = PaddleMovementSpeed * Time.Delta;
35			var distance = clickPosition.X - xPosition;
36			if (distance.Abs() < moveDistAbsolute)
37			{
38				xPosition = clickPosition.X;
39				return;
40			}
41			xPosition += distance > 0 ? moveDistAbsolute : -moveDistAbsolute;
42		}
43
44		private void RegisterButtonCommands()
45		{
46			var left = new Command(() => xPosition -= PaddleMovementSpeed * Time.Delta);
47			left.Add(new KeyTrigger(Key.CursorLeft, State.Pressed));
48			left.Add(new GamePadButtonTrigger(GamePadButton.Left, State.Pressed));
49			var right = new Command(() => xPosition += PaddleMovementSpeed * Time.Delta);
50			right.Add(new KeyTrigger(Key.CursorRight, State.Pressed));
51			right.Add(new GamePadButtonTrigger(GamePadButton.Right, State.Pressed));
52		}
53
54		private float xPosition = 0.5f;
55		private const float PaddleMovementSpeed = 1.5f;
56
57		public class RunPaddle : UpdateBehavior
58		{
59			public override void Update(IEnumerable<Entity> entities)
60			{
61				foreach (var entity in entities)
62				{
63					var paddle = (Paddle)entity;
64					var xPosition = paddle.xPosition.Clamp(HalfWidth, 1.0f - HalfWidth);
65					paddle.xPosition = xPosition;
66					paddle.DrawArea = Rectangle.FromCenter(xPosition, YPosition, Width, Height);
67				}
68			}
69		}
70
71		private const float YPosition = 0.9f;
72		internal const float HalfWidth = Width / 2.0f;
73		private const float Width = 0.2f;
74		private const float Height = 0.04f;
75
76		public Vector2D Position
77		{
78			get { return new Vector2D(DrawArea.Center.X, DrawArea.Top); }
79		}
80	}
81}