The player can move around in only 4 directions. Its how I want it. So I have this small input setup.
private void UpdateInput()
{
input = Keyboard.GetState();
if (gplayer.active)
{
if (input.IsKeyDown(Keys.Up))
{
gplayer.direction = 3;
playerSprite.Y -= 4;
}
if (input.IsKeyDown(Keys.Down))
{
gplayer.direction = 0;
playerSprite.Y += 4;
}
if (input.IsKeyDown(Keys.Left))
{
gplayer.direction = 1;
playerSprite.X -= 4;
}
if (input.IsKeyDown(Keys.Right))
{
gplayer.direction = 2;
playerSprite.X += 4;
}
}
}
Which works okay, except when you hold down Up and Left or Up and Right etc. How do I make it check to see if each key is the only button being pressed at that time?
And the playerSprite.X is going to be replaced with something else. Which leads me to my next question. How would I make the player move along a grid like in rmxp. I want the player to move along a 16x16 grid.
Thanks for the help in advance!
Use "else if" instead of "if" in the following branches.
A more elegant solution would be:
Vector2 movement = Vector2.Zero;
if (input.IsKeyDown(Keys.Up))
movement.Y -= 1;
if (input.IsKeyDown(Keys.Down))
movement.Y += 1;
if (input.IsKeyDown(Keys.Left))
movement.X -= 1;
if (input.IsKeyDown(Keys.Right))
movement.X += 1;
if (movement != Vector2.Zero && !(movement.X != 0 && movement.Y != 0))
{
gplayer.direction = movement.X + 2*movement.Y + 2; // feel free to change this, this is just one possible way to make an integer direction.
playerSprite += 4 * movement;
}
for the grid, you want to store the player's position in terms of the grid, (like pos = tile (3,4)), and then make the grid length a constant. For movement, pick a move speed that will evenly go into the grid length, and then add it to the player's real position each frame until it matches the grid position.
Math.Floor(real position / grid length) = grid position
(you only need Math.Floor if either real position or grid length is NOT an int.
I'd use a constant or variable for the 4 since it represents moving speed. :)