Question

I'm working on a 2d game and I want the player to be able to be moved with the arrow keys.

I've managed to make the player move by the left thumb stick (Xbox 360 controller)

GamePadState gamePadState = GamePad.GetState(PlayerIndex.One);
hero.position.X += gamePadState.ThumbSticks.Left.X * 20;

But I can't figure out how to move it with a arrow keys.

Anyone thing the could help me? :)

Was it helpful?

Solution

To handle the keyboard, you can use the Keyboard.GetState() which returns KeyboardState. Once you have the keyboard state you can call KeyboardState.IsKeyDown() to determine if the key you are interested in has been pressed. If the key is pressed, then you adjust the x and y coordinates accordingly.

Remember the thumb sticks are analogue inputs so you can get a range of values indicating how far left, right, up or down the stick has been moved, which allows the player some control over the "speed". The keyboard is digital so it is either pressed, or not so the character is either moving or not. There are tricks to make this feel similar on the keyboard, but first get your character moving, then you can delve into that if you even require it.

You should also take a look at the Platform starter kit that comes with XNA, that code should give you a few ideas around how to handle input devices.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top