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.

82 lines
2.3 KiB

  1. using Microsoft.Xna.Framework;
  2. using Microsoft.Xna.Framework.Graphics;
  3. using System.Collections.Generic;
  4. namespace SemiColinGames {
  5. class IdleState : IState<NPC> {
  6. float timeInState = 0;
  7. public void Enter() {
  8. timeInState = 0;
  9. }
  10. public string? Update(NPC npc, float modelTime, World world) {
  11. timeInState += modelTime;
  12. if (timeInState > 1.0f) {
  13. npc.Facing *= -1;
  14. return "run";
  15. }
  16. return null;
  17. }
  18. }
  19. class RunState : IState<NPC> {
  20. public void Enter() {}
  21. public string? Update(NPC npc, float modelTime, World world) {
  22. int moveSpeed = 120;
  23. int desiredX = npc.Position.X + (int) (moveSpeed * npc.Facing * modelTime);
  24. // TODO: define the box modularly & correctly.
  25. AABB npcBox = new AABB(new Vector2(desiredX, npc.Position.Y), new Vector2(1, 33));
  26. Debug.AddRect(npcBox, Color.Cyan);
  27. bool foundBox = false;
  28. foreach (AABB box in world.CollisionTargets) {
  29. if (box.Intersect(npcBox) != null) {
  30. foundBox = true;
  31. break;
  32. }
  33. }
  34. if (!foundBox) {
  35. return "idle";
  36. }
  37. npc.Position.X = desiredX;
  38. return null;
  39. }
  40. }
  41. public class NPC {
  42. private const int spriteWidth = 96;
  43. private const int spriteHeight = 81;
  44. private const int spriteCenterYOffset = 2;
  45. private FSM<NPC> fsm;
  46. public NPC(Point position) {
  47. Position = position;
  48. fsm = new FSM<NPC>(new Dictionary<string, IState<NPC>> {
  49. { "idle", new IdleState() },
  50. { "run", new RunState() }
  51. }, "run");
  52. }
  53. public int Facing = 1;
  54. public Point Position;
  55. public void Update(float modelTime, World world) {
  56. fsm.Update(this, modelTime, world);
  57. }
  58. public void Draw(SpriteBatch spriteBatch) {
  59. Rectangle textureSource = Sprites.Executioner.GetTextureSource(
  60. fsm.StateName, Clock.ModelTime.TotalSeconds);
  61. // TODO: move this into Sprite metadata.
  62. Vector2 spriteCenter = new Vector2(spriteWidth / 2, spriteHeight / 2 + spriteCenterYOffset);
  63. SpriteEffects effect = Facing == 1 ?
  64. SpriteEffects.None : SpriteEffects.FlipHorizontally;
  65. Color color = Color.White;
  66. spriteBatch.Draw(Textures.Executioner.Get, Position.ToVector2(), textureSource, color, 0f,
  67. spriteCenter, Vector2.One, effect, 0f);
  68. }
  69. }
  70. }