我目前正在使用Windows控制台制作平台游戏。但是,当我发出多个命令时,我遇到了一个问题。
例如,当我让我的角色在一个方向上运行然后按下跳跃时,忘记了运行键并且必须再次按下这一事实。
是否有输入法可以检查正在按住或按下哪些键?或者更确切地说,是一种检查重复输入的方法吗?
供参考,这是我目前的代码: http://pastebin.com/2y6Rf6rb
我目前使用的输入法是:
/*** Keyboard Input ***/
/* Number of Events */
DWORD numEvents = 0;
/* Events from Console Read */
DWORD numEventsRead = 0;
/* Find Number of Console Events */
GetNumberOfConsoleInputEvents(rHnd, &numEvents);
/*If there is an Event */
if(numEvents != 0)
{
/* Create Buffer to Store Events */
INPUT_RECORD *eventBuffer = new INPUT_RECORD[numEvents];
/* Read Console Events to that Buffer and Save that many Events */
ReadConsoleInput(rHnd, eventBuffer, numEvents, &numEventsRead);
/* Cycle through Events that have Happened */
for(DWORD i = 0; i < numEventsRead; i++)
{
/* If Event was a Key Press */
if(eventBuffer[i].EventType == KEY_EVENT && eventBuffer[i].Event.KeyEvent.bKeyDown == TRUE)
{
/* Right ('d' Key) 0x44*/
if(eventBuffer[i].Event.KeyEvent.wVirtualKeyCode == 0x44)
{
key = 'd';
for(y = 0; y < 3; y ++)
{
if(gdisplay[PY - y][PX + 4] == square1[0] && gdisplay[PY - y][PX + 4 + 1] == square1[1])
{
movecheck = 0;
}
}
if(momentum < 0)
{
momentum++;
}
else if(movecheck == 1)
{
PX+=2;
momentum++;
if(panime == 1)
{
panime = 2;
}
else if(panime == 2)
{
panime = 1;
}
}
}
/* Left ('a' Key) 0x41*/
else if(eventBuffer[i].Event.KeyEvent.wVirtualKeyCode == 0x41)
{
key = 'a';
if((PX - 2) >= 2)
{
for(y = 0; y < 3; y ++)
{
if(gdisplay[PY - y][PX - 4] == square1[0] && gdisplay[PY - y][PX - 4 + 1] == square1[1])
{
movecheck = 0;
}
}
if(momentum > 0)
{
momentum--;
}
else if(movecheck == 1)
{
PX-=2;
momentum--;
if(panime == 1)
{
panime = 2;
}
else if(panime == 2)
{
panime = 1;
}
}
}
}
/* Jump (Spacebar) VK_SPACE*/
else if(eventBuffer[i].Event.KeyEvent.wVirtualKeyCode == VK_SPACE)
{
if(jump == 0)
{
jump++;
PY-=2;
}
}
}
/* Max Momentum */
if(momentum > 4)
{
momentum = 4;
}
if(momentum < -4)
{
momentum = -4;
}
rewind(stdin);
}
}
答案 0 :(得分:1)
您可以尝试的一件事是,在发出keyDown
时,您可以将某些标记设置为true,例如rightKeyPressed = true
,然后您还可以检查keyUp
,在这种情况下,您可以执行rightKeyPressed = false
并为每个正在运行的键执行此操作。我相信你遇到的问题是当你按下你所持有的键以外的键时,你不再接收该键的keyDown事件。因此,您需要一些方法来保存特定键被按下,直到它实际释放。这样,当您使用跳转命令中断时,即使系统没有收到该密钥的rightKeyPressed
事件,keyDown
(或任何方向)仍然为真。
这需要进行一些重要的重构,因为您目前只跟踪key
变量。举个例子,这里有一些假代码可以证明这一点:
public void keyPressed(Key key){
if(key==RIGHT)
runningRight = true;
runningLeft = false;
else if(key==LEFT)
runningLeft = true;
runningRight = false;
else if(e.getKeyCode()==CTRL)
jump = true;
}
public void keyReleased(KeyEvent e){
if(key==RIGHT)
runningRight = false;
else if(key==LEFT)
runningLeft = false;
}
祝你好运