PageRenderTime 42ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/Samples/Breakout/Paddle.cs

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