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.

83 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, int facing) {
  47. Position = position;
  48. Facing = facing;
  49. fsm = new FSM<NPC>(new Dictionary<string, IState<NPC>> {
  50. { "idle", new IdleState() },
  51. { "run", new RunState() }
  52. }, "run");
  53. }
  54. public int Facing;
  55. public Point Position;
  56. public void Update(float modelTime, World world) {
  57. fsm.Update(this, modelTime, world);
  58. }
  59. public void Draw(SpriteBatch spriteBatch) {
  60. Rectangle textureSource = Sprites.Executioner.GetTextureSource(
  61. fsm.StateName, Clock.ModelTime.TotalSeconds);
  62. // TODO: move this into Sprite metadata.
  63. Vector2 spriteCenter = new Vector2(spriteWidth / 2, spriteHeight / 2 + spriteCenterYOffset);
  64. SpriteEffects effect = Facing == 1 ?
  65. SpriteEffects.None : SpriteEffects.FlipHorizontally;
  66. Color color = Color.White;
  67. spriteBatch.Draw(Textures.Executioner.Get, Position.ToVector2(), textureSource, color, 0f,
  68. spriteCenter, Vector2.One, effect, 0f);
  69. }
  70. }
  71. }