I just found the article here about the component base system. Sadly I cant find any example of component base system implemented in XNA so i decided to make my own. Im not really sure if this is the correct implementation of component base system but it will help me improve if someone can point what are my mistakes. Here is my diagram (note this is just a simple diagram)
Here is my simple code for pong
The input class
class InputHandler : IKeyInputhandler
{
Dictionary<Keys,Vector2> keyDictionary = new Dictionary<Keys, Vector2>();
private bool left, right;
public InputHandler()
{
keyDictionary.Add(Keys.Space, new Vector2(-1,0));
keyDictionary.Add(Keys.Right, new Vector2(1, 0));
}
public bool moveLeft
{
get { return left; }
}
public bool moveRight
{
get { return right; }
}
public void Update()
{
KeyboardState state = Keyboard.GetState();
foreach (KeyValuePair<Keys, Vector2> keyValuePair in keyDictionary)
{
if (state.IsKeyDown(keyValuePair.Key))
{
if (keyValuePair.Key == Keys.Space)
{
left = true;
}
if (keyValuePair.Key == Keys.D)
{
right = true;
}
}
else
{
if (keyValuePair.Key == Keys.Space)
{
left = false;
}
}
}
}
}
The interface for input
public interface IKeyInputhandler
{
bool moveLeft { get; }
bool moveRight { get; }
void Update();
}
Player class
public class Player
{
private readonly IKeyInputhandler keyInputhandler;
public Player(IKeyInputhandler keyInputhandler)
{
this.keyInputhandler = keyInputhandler;
}
public void Update(GameTime gameTime)
{
keyInputhandler.Update();
if (keyInputhandler.moveLeft)
{
Debug.WriteLine("moving left");
}
}
}
The implementation in game class
player = new Player(new InputHandler());
In this tutorial I decided just to send messages via boolean variable property from InputHandler
Is this good? Am i doing this right?