简体   繁体   English

游戏循环中的 C# KeyDown 事件

[英]C# KeyDown Event in Game loop

I'm working on a game in C# and have gotten stuck.我正在用 C# 开发一个游戏,但被卡住了。 So the background is consistently moving, and this is done in a loop wit a Timer to insure that the background moves consistently.所以背景一直在移动,这是在一个带有计时器的循环中完成的,以确保背景始终如一地移动。 Now, I need to check if the user has pressed Spacebar to move the player up.现在,我需要检查用户是否按下了空格键来向上移动播放器。 How do I check if there is a keydown event?如何检查是否有 keydown 事件? I can't use a KeyDown event sub because the game loop is consistently working, so the KeyDown event sub won't work.我不能使用 KeyDown 事件子,因为游戏循环一直在工作,所以 KeyDown 事件子不起作用。 Just looking for some direction here.只是在这里寻找一些方向。 Thanks!谢谢!

In your tick event you can check for在您的滴答事件中,您可以检查

if (Keyboard.IsKeyDown(Key.Space))
{
    ... Do stuff
}

Just guessing as you didn't provided any code.只是猜测,因为您没有提供任何代码。

Try to call Application.DoEvents();尝试调用Application.DoEvents(); in every loop and use the KeyDown as you intend.在每个循环中并按您的意愿使用KeyDown

EDIT:编辑:

OK, this means you are NOT using the game loop, but you have event driven application (usual win application).好的,这意味着您没有使用游戏循环,但是您有事件驱动的应用程序(通常是获胜应用程序)。 Call to Application.DoEvents() lets the windows to process all callbacks in regular game loop (not your case).调用Application.DoEvents()允许窗口处理常规游戏循环中的所有回调(不是你的情况)。

I have updated code again to show how it works - I believe learning by examples is good, but first, you must learn the basics (sorry, but the game is too complicated for learning the C#)...我再次更新了代码来展示它是如何工作的——我相信通过例子学习是好的,但首先,你必须学习基础知识(抱歉,这个游戏对于学习 C# 来说太复杂了)......

private bool isKeyUpPressed;
private void tmrTick_Tick(object sender, EventArgs e) { 
    if (isKeyUpPressed)
    {
        // move player up
    }
} 
private void Form1_KeyDown(object sender, KeyEventArgs b) { 
    isKeyUpPressed = b.KeyCode == Keys.Up;
}

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

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