if (Keyboard.GetState().IsKeyDown(Keys.Down))
{
positionoutercursor.Y += 40 ;
}
if (positionoutercursor.Y >=260)
{
positionoutercursor.Y = 260;
}
if (Keyboard.GetState().IsKeyDown(Keys.Up))
{
positionoutercursor.Y -= 40;
}
if (positionoutercursor.Y <= 15)
{
positionoutercursor.Y = 15;
}
But when i press up or down the sprite moves much more than i want. The problem is that I want it move only 40 pixels to up or down each time I press these keys. I dont want it to continue adding 40 all the time according to time I press the key. Anyone can help me with this very simple question? (It ddoent pass the board limits I put but move 80 or 120 pixels each time)
private KeyboardState _previousKeyboardState;
var keyboardState = Keyboard.GetState();
var moveDirection = Vector2.Zero;
if (keyboardState.IsKeyDown(Keys.Up) && _previousKeyboardState.IsKeyUp(Keys.Up))
moveDirection -= Vector2.UnitY;
if (keyboardState.IsKeyDown(Keys.Down) && _previousKeyboardState.IsKeyUp(Keys.Down))
moveDirection += Vector2.UnitY;
var deltaSeconds = (float)gameTime.ElapsedGameTime.TotalSeconds;
var speed = 40;
position += moveDirection * speed * deltaSeconds;
_previousKeyboardState = keyboardState;
1 Like
thats ok, thanks for the help. Isnt there any other simple way to do this? like, when key is pressed do this and then key is inactive!
Yeah I understand it seems like a lot of code just to check something simple as a when a key is pressed but that’s how to do it in XNA / MonoGame; you need 2 frames where the current frame has to have the key in a down state and the previous frame has to have the key in a up state.
1 Like