user1150769
user1150769

Reputation: 395

XNA set key to released?

I am writing a simple game in XNA where you move a sprite around using WSAD. The problem is if two keys of the same direction are pressed at the same time, the movement cancels out and the character does not move. Is it possible to manually set a key to released to avoid this? Here is the key movement code:

if (newKeyState.IsKeyDown(Keys.W))
{
     position.Y -= vel;
}
if (newKeyState.IsKeyDown(Keys.S))
{
     position.Y += vel;
}
if (newKeyState.IsKeyDown(Keys.A))
{
     position.X -= vel;
}
if (newKeyState.IsKeyDown(Keys.D))
{
     position.X += vel;
}

Upvotes: 1

Views: 733

Answers (2)

Stuart Golodetz
Stuart Golodetz

Reputation: 20616

The key state (newKeyState in your above code) represents the actual physical state of the keyboard, so it's neither possible nor desirable to set a key's state to released when the user is still holding it down. There are however some alternatives that will allow you to achieve the desired end result:

1) You can restructure your code, e.g.

if(newKeyState.IsKeyDown(Keys.W))
{
    position.Y -= vel;
}
else if(newKeyState.IsKeyDown(Keys.S))
{
    position.Y += vel;
}
// etc.

2) You can maintain your own state (i.e. a cached version of newKeyState) and set keys to released in that.

Upvotes: 1

ClassicThunder
ClassicThunder

Reputation: 1936

Is it possible to manually set a key to released to avoid this?

Nope. However, you can change it to an else-if. In this case is W && S are pressed then only W will count. you can alter this by changing what key is checked first.

if (newKeyState.IsKeyDown(Keys.W)) {
     position.Y -= vel;
} else if (newKeyState.IsKeyDown(Keys.S)) {
     position.Y += vel;
} else if (newKeyState.IsKeyDown(Keys.A)) {
     position.X -= vel;
} else if (newKeyState.IsKeyDown(Keys.D)) {
     position.X += vel;
}

If you only want to only move one direction on each axis.

if (newKeyState.IsKeyDown(Keys.W)) {
     position.Y -= vel;
} else if (newKeyState.IsKeyDown(Keys.S)) {
     position.Y += vel;
} 

if (newKeyState.IsKeyDown(Keys.A)) {
     position.X -= vel;
} else if (newKeyState.IsKeyDown(Keys.D)) {
     position.X += vel;
}

Upvotes: 1

Related Questions