简体   繁体   English

C#中KeyDown()的简单但棘手的问题#

[英]Simple but tricky issue with KeyDown() in C#

I am doing a little game with sprites where the character moves depending on the pressed key (arrows). 我正在用精灵做一个小游戏,角色根据按下的键移动(箭头)。 I've noticed that the .KeyDown() method keeps being called until any key is released. 我注意到.KeyDown()方法一直被调用,直到释放任何键。

eg When the user is pressing the up arrow, the method of .KeyDown() keeps being called. 例如,当用户按下向上箭头时, .KeyDown()的方法不断被调用。 If the down arrow is pressed, still with the up arrow pressed, the KeyEventArgs receives now the input from the down arrow. 如果按下向下箭头,仍然按下向上箭头, KeyEventArgs现在从向下箭头接收输入。 Finally, when the up arrow is released, the .KeyDown() event stops being called even though the down arrow is still pressed. 最后,当释放向上箭头时, 即使仍然按下向下箭头, .KeyDown()事件也会停止被调用。

How do I "reset" the input and tell the compiler to keep calling .KeyDown() ? 如何“重置”输入并告诉编译器继续调用.KeyDown()

A very good question- I don't believe that there's any way to override this default behavior, but it would certainly be possible to avoid this effect by keeping track of key presses yourself- ie, when .KeyDown() is called, add the key to some type of structure which keeps track of it- and then, when .KeyUp() is called, remove the key from that structure. 一个非常好的问题 - 我不相信有任何方法可以覆盖这个默认行为,但是通过跟踪按键自己肯定可以避免这种影响 - 即,当.KeyDown()时,添加某些类型的结构的关键,它跟踪它 - 然后,当.KeyUp()时,从该结构中删除键。

Then, just repeatedly check that structure for the currently pressed keys, and base your movement off of that , not what .KeyDown() is telling you. 然后,只需反复检查当前按下的键的结构,并将您的运动基于 ,而不是.KeyDown()告诉您的。

You can try to use KeyUp in order to detect when the key is released. 您可以尝试使用KeyUp来检测密钥何时被释放。 Then you can assume the key is still pressed until KeyUp is called. 然后你可以假设按键仍然被按下,直到调用KeyUp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM