I'm trying to learn XNA game programming, now i would like to wait while a Key is Pressed I have Test it with:
while (IsKeyPressed = Keyboard.GetState().IsKeyDown(key));
But IsKeyPressed is also true when the key was released
That code is effectively a spin lock. Don't use spin-locks .
The bug you are seeing is likely because you are using a spin-lock, its not getting a chance to update properly.
Instead, you should read the key being pressed, and set state in whatever class is relevant to stop processing (likely a simple if
check in the Update
function). Then, when you detect the release, you change the state so the if
check will pass.
Something like:
//Main Update
if (Keyboard.GetState().IsKeyDown(key))
myObject.Wait();
else
myObject.Continue();
//Other object
public void Wait()
{
waiting = true;
}
public void Continue()
{
waiting = false;
}
public void Update()
{
if (!waiting)
{
//Update state
}
}
You could always check previous state to avoid calling Wait
and Continue
repeatedly, but thats going to be something of a micro-optimization with the code provided.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.