sneak/Shared/NPC.cs

83 lines
2.3 KiB
C#
Raw Normal View History

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
2020-03-05 22:39:17 +00:00
using System.Collections.Generic;
namespace SemiColinGames {
2020-03-05 22:39:17 +00:00
class IdleState : IState {
float timeInState = 0;
2020-03-05 22:39:17 +00:00
public void Enter() {
timeInState = 0;
}
2020-03-05 22:39:17 +00:00
public string? Update(NPC npc, float modelTime, AABB[] collisionTargets) {
timeInState += modelTime;
if (timeInState > 1.0f) {
npc.Facing *= -1;
return "run";
}
return null;
}
2020-03-05 22:39:17 +00:00
}
2020-03-05 22:39:17 +00:00
class RunState : IState {
public void Enter() {}
2020-03-05 22:39:17 +00:00
public string? Update(NPC npc, float modelTime, AABB[] collisionTargets) {
int moveSpeed = 120;
2020-03-05 22:39:17 +00:00
int desiredX = npc.Position.X + (int) (moveSpeed * npc.Facing * modelTime);
// TODO: define the box modularly & correctly.
2020-03-05 22:39:17 +00:00
AABB npcBox = new AABB(new Vector2(desiredX, npc.Position.Y), new Vector2(1, 33));
Debug.AddRect(npcBox, Color.Cyan);
bool foundBox = false;
foreach (AABB box in collisionTargets) {
if (box.Intersect(npcBox) != null) {
foundBox = true;
break;
}
}
if (!foundBox) {
2020-03-05 22:39:17 +00:00
return "idle";
}
2020-03-05 22:39:17 +00:00
npc.Position.X = desiredX;
return null;
}
}
public class NPC {
private const int spriteWidth = 96;
private const int spriteHeight = 81;
private const int spriteCenterYOffset = 2;
private FSM fsm;
public NPC(Point position) {
Position = position;
fsm = new FSM(new Dictionary<string, IState> {
{ "idle", new IdleState() },
{ "run", new RunState() }
2020-03-06 16:44:19 +00:00
}, "run");
2020-03-05 22:39:17 +00:00
}
public int Facing = 1;
public Point Position;
public void Update(float modelTime, AABB[] collisionTargets) {
fsm.Update(this, modelTime, collisionTargets);
}
public void Draw(SpriteBatch spriteBatch) {
Rectangle textureSource = Sprites.Executioner.GetTextureSource(
fsm.StateName, Clock.ModelTime.TotalSeconds);
// TODO: move this into Sprite metadata.
Vector2 spriteCenter = new Vector2(spriteWidth / 2, spriteHeight / 2 + spriteCenterYOffset);
SpriteEffects effect = Facing == 1 ?
SpriteEffects.None : SpriteEffects.FlipHorizontally;
Color color = Color.White;
2020-03-05 22:39:17 +00:00
spriteBatch.Draw(Textures.Executioner.Get, Position.ToVector2(), textureSource, color, 0f,
spriteCenter, Vector2.One, effect, 0f);
}
}
}