A stealth-based 2D platformer where you don't have to kill anyone unless you want to. https://www.semicolin.games
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

256 lines
8.5 KiB

  1. using Microsoft.Xna.Framework;
  2. using Microsoft.Xna.Framework.Graphics;
  3. using System;
  4. using System.Collections.Generic;
  5. namespace SemiColinGames {
  6. interface IPlayerState : IState<History<Input>> {
  7. public Vector2 Movement { get; }
  8. public void PostUpdate(bool standingOnGround);
  9. }
  10. class StandState : IPlayerState {
  11. private Vector2 result;
  12. // private double swordSwingTime = 0;
  13. // private int swordSwingNum = 0;
  14. private float ySpeed = 0;
  15. private int jumps = 1;
  16. private const int jumpSpeed = -600;
  17. private const int moveSpeed = 180;
  18. private const int gravity = 1600;
  19. public void Enter() {
  20. }
  21. public string Update(float modelTime, World world, History<Input> input) {
  22. result = new Vector2() {
  23. X = input[0].Motion.X * moveSpeed * modelTime
  24. };
  25. if (input[0].Jump && !input[1].Jump && jumps > 0) {
  26. jumps--;
  27. ySpeed = jumpSpeed;
  28. }
  29. // if (input[0].Attack && !input[1].Attack && swordSwingTime <= 0) {
  30. // swordSwingTime = 0.3;
  31. // swordSwingNum++;
  32. // SoundEffects.SwordSwings[swordSwingNum % SoundEffects.SwordSwings.Length].Play();
  33. // }
  34. result.Y = ySpeed * modelTime;
  35. ySpeed += gravity * modelTime;
  36. // swordSwingTime -= modelTime;
  37. if (input[0].IsAbsoluteMotion) {
  38. if (input[1].Motion.X == 0) {
  39. result.X = input[0].Motion.X;
  40. } else {
  41. result.X = 0;
  42. }
  43. }
  44. return null;
  45. }
  46. public Vector2 Movement {
  47. get { return result; }
  48. }
  49. // TODO: Maybe this should be Update(), and CalculateMovement() should be the Player-specific
  50. // function?
  51. public void PostUpdate(bool standingOnGround) {
  52. if (standingOnGround) {
  53. jumps = 1;
  54. ySpeed = -0.0001f;
  55. // Debug.AddRect(Box(position), Color.Cyan);
  56. } else {
  57. jumps = 0;
  58. // Debug.AddRect(Box(position), Color.Orange);
  59. }
  60. }
  61. }
  62. public class Player {
  63. private readonly FSM<History<Input>> fsm;
  64. // Details of the sprite image.
  65. // player_1x is 48 x 48, yOffset=5, halfSize=(7, 14)
  66. // Ninja_Female is 96 x 64, yOffset=1, halfSize=(11, 24)
  67. private const int spriteWidth = 96;
  68. private const int spriteHeight = 64;
  69. private const int spriteCenterYOffset = 1;
  70. // Details of the actual Player model.
  71. // Position is tracked at the Player's center. The Player's bounding box is a rectangle
  72. // centered at that point and extending out by halfSize.X and halfSize.Y.
  73. private Vector2 position;
  74. private Vector2 halfSize = new Vector2(11, 24);
  75. // Fractional-pixel movement that was left over from a previous frame's movement.
  76. // Useful so that we can run at a slow time-step and still get non-zero motion.
  77. private Vector2 residual = Vector2.Zero;
  78. private float invincibilityTime = 0;
  79. // For passing into Line.Rasterize() during movement updates.
  80. private readonly IList<Point> movePoints = new ProfilingList<Point>(64, "Player.movePoints");
  81. // Possible hitboxes for player <-> obstacles.
  82. private readonly IList<AABB> candidates = new ProfilingList<AABB>(16, "Player.candidates");
  83. public Player(Vector2 position, int facing) {
  84. this.position = position;
  85. Facing = facing;
  86. Health = MaxHealth;
  87. StandingOnGround = false;
  88. fsm = new FSM<History<Input>>("run", new Dictionary<string, IState<History<Input>>> {
  89. { "run", new StandState() },
  90. });
  91. }
  92. public bool StandingOnGround { get; private set; }
  93. public int MaxHealth { get; private set; } = 3;
  94. public int Health { get; private set; }
  95. public int Facing { get; private set; }
  96. public Vector2 Position { get { return position; } }
  97. public void Update(float modelTime, World world, History<Input> input) {
  98. AABB BoxOffset(Vector2 position, int yOffset) {
  99. return new AABB(new Vector2(position.X, position.Y + yOffset), halfSize);
  100. }
  101. AABB Box(Vector2 position) {
  102. return BoxOffset(position, 0);
  103. }
  104. invincibilityTime -= modelTime;
  105. Vector2 inputMovement = HandleInput(modelTime, world, input);
  106. Vector2 movement = Vector2.Add(residual, inputMovement);
  107. residual = new Vector2(movement.X - (int) movement.X, movement.Y - (int) movement.Y);
  108. // Broad test: remove all collision targets nowhere near the player.
  109. candidates.Clear();
  110. // Expand the box in the direction of movement. The center is the midpoint of the line
  111. // between the player's current position and their desired movement. The width increases by
  112. // the magnitude of the movement in each direction. We add 1 to each dimension just to be
  113. // sure (the only downside is a small number of false-positive AABBs, which should be
  114. // discarded by later tests anyhow.)
  115. AABB largeBox = new AABB(
  116. Vector2.Add(position, Vector2.Divide(movement, 2)),
  117. Vector2.Add(halfSize, new Vector2(Math.Abs(movement.X) + 1, Math.Abs(movement.Y) + 1)));
  118. foreach (var box in world.CollisionTargets) {
  119. if (box.Intersect(largeBox) != null) {
  120. // Debug.AddRect(box, Color.Green);
  121. candidates.Add(box);
  122. }
  123. }
  124. bool harmedByCollision = false;
  125. Line.Rasterize(0, 0, (int) movement.X, (int) movement.Y, movePoints);
  126. for (int i = 1; i < movePoints.Count; i++) {
  127. int dx = movePoints[i].X - movePoints[i - 1].X;
  128. int dy = movePoints[i].Y - movePoints[i - 1].Y;
  129. if (dy != 0) {
  130. Vector2 newPosition = new Vector2(position.X, position.Y + dy);
  131. AABB player = Box(newPosition);
  132. bool reject = false;
  133. foreach (var box in candidates) {
  134. if (box.Intersect(player) != null) {
  135. Debug.AddRect(box, Color.Cyan);
  136. reject = true;
  137. if (box.Tile?.IsHazard ?? false) {
  138. Debug.AddRect(box, Color.Red);
  139. harmedByCollision = true;
  140. }
  141. }
  142. }
  143. if (!reject) {
  144. position = newPosition;
  145. }
  146. }
  147. if (dx != 0) {
  148. Vector2 newPosition = new Vector2(position.X + dx, position.Y);
  149. AABB player = Box(newPosition);
  150. bool reject = false;
  151. foreach (var box in candidates) {
  152. if (box.Intersect(player) != null) {
  153. Debug.AddRect(box, Color.Cyan);
  154. reject = true;
  155. if (box.Tile?.IsHazard ?? false) {
  156. Debug.AddRect(box, Color.Red);
  157. harmedByCollision = true;
  158. }
  159. }
  160. }
  161. if (!reject) {
  162. position = newPosition;
  163. }
  164. }
  165. }
  166. StandingOnGround = false;
  167. AABB groundIntersect = BoxOffset(position, 1);
  168. foreach (var box in candidates) {
  169. if (groundIntersect.Intersect(box) != null) {
  170. Debug.AddRect(box, Color.Cyan);
  171. StandingOnGround = true;
  172. if (box.Tile?.IsHazard ?? false) {
  173. Debug.AddRect(box, Color.Red);
  174. harmedByCollision = true;
  175. }
  176. }
  177. }
  178. ((IPlayerState) fsm.State).PostUpdate(StandingOnGround);
  179. if (harmedByCollision && invincibilityTime <= 0) {
  180. world.ScreenShake();
  181. Health -= 1;
  182. invincibilityTime = 0.6f;
  183. }
  184. if (inputMovement.X > 0) {
  185. Facing = 1;
  186. } else if (inputMovement.X < 0) {
  187. Facing = -1;
  188. }
  189. }
  190. // Returns the desired (dx, dy) for the player to move this frame.
  191. Vector2 HandleInput(float modelTime, World world, History<Input> input) {
  192. fsm.Update(modelTime, world, input);
  193. // TODO: remove ugly cast.
  194. return ((IPlayerState) fsm.State).Movement;
  195. }
  196. private Rectangle GetTextureSource() {
  197. double time = Clock.ModelTime.TotalSeconds;
  198. IPlayerState state = (IPlayerState) fsm.State;
  199. if (StandingOnGround && state.Movement.X == 0) {
  200. return Sprites.Ninja.GetTextureSource("idle", time);
  201. } else {
  202. return Sprites.Ninja.GetTextureSource("run", time);
  203. }
  204. }
  205. public void Draw(SpriteBatch spriteBatch) {
  206. Rectangle textureSource = GetTextureSource();
  207. Vector2 spriteCenter = new Vector2(spriteWidth / 2, spriteHeight / 2 + spriteCenterYOffset);
  208. SpriteEffects effect = Facing == 1 ?
  209. SpriteEffects.None : SpriteEffects.FlipHorizontally;
  210. Color color = Color.White;
  211. if (invincibilityTime > 0 && invincibilityTime % 0.2f > 0.1f) {
  212. color = new Color(0.5f, 0.5f, 0.5f, 0.5f);
  213. }
  214. spriteBatch.Draw(Textures.Ninja.Get, Vector2.Floor(position), textureSource, color, 0f,
  215. spriteCenter, Vector2.One, effect, 0f);
  216. }
  217. }
  218. }