Clean Up Your Player Movement Code
How many times have you had to enter a line in your game to handle player movement that looks something like this:
if ((keyboardState.IsKeyDown(Keys.A)) ||
(gamePadState.DPad.Left == ButtonState.Pressed) ||
(gamePadState.ThumbSticks.Left.X < 0))
It's long and awkward to read and can be a pain to change. Wouldn't you rather just do this?
if (LeftPressed(currentKeyboardState, currentGamePadState))
I know I would! And now, thanks to the magic of a couple very simple functions that I will display below, now you can!
private bool LeftPressed(KeyboardState keyboardState, GamePadState gamePadState)
{
if (keyboardState.IsKeyDown(Keys.A))
{
return true;
}
if (gamePadState.DPad.Left == ButtonState.Pressed)
{
return true;
}
if (gamePadState.ThumbSticks.Left.X < 0)
{
return true;
}
return false;
}
private bool RightPressed(KeyboardState keyboardState, GamePadState gamePadState)
{
if (keyboardState.IsKeyDown(Keys.D))
{
return true;
}
if (gamePadState.DPad.Right == ButtonState.Pressed)
{
return true;
}
if (gamePadState.ThumbSticks.Left.X > 0)
{
return true;
}
return false;
}
private bool UpPressed(KeyboardState keyboardState, GamePadState gamePadState)
{
if (keyboardState.IsKeyDown(Keys.W))
{
return true;
}
if (gamePadState.DPad.Up == ButtonState.Pressed)
{
return true;
}
if (gamePadState.ThumbSticks.Left.Y > 0)
{
return true;
}
return false;
}
private bool DownPressed(KeyboardState keyboardState, GamePadState gamePadState)
{
if (keyboardState.IsKeyDown(Keys.S))
{
return true;
}
if (gamePadState.DPad.Down == ButtonState.Pressed)
{
return true;
}
if (gamePadState.ThumbSticks.Left.Y < 0)
{
return true;
}
return false;
}
These four functions should handle all your basic movement needs (though will require some modification if you plan to take advantage of the analog nature of the thumbsticks).
This article has been view 883 times.
|