这是我在 C++ 中移动使用 DirectX 11 绘制的简单三角形的尝试:
int DrawAndMovePlayer(Renderer renderer)
{
Triangle triangle1(renderer);
float p1, p2, p3, p4, p5, p6;
float x, y;
x = 0.0f;
y = 0.0f;
if (GetAsyncKeyState(0x58))
{
x = 1.0f;
}
// Top
p1 = x + 0.0f;
p2 = y + 0.05f;
// Bottom Right
p3 = x + 0.05f;
p4 = y - 0.05f;
// Top
p5 = x - 0.05f;
p6 = y - 0.05f;
// Triangle triangle2(renderer);
triangle1.draw(renderer, p1, p2, p3, p4, p5, p6);
//triangle2.draw(renderer, -0.5f);
return 0;
}
我已经尝试了 getch()
函数和 GetAsyncKeyState()
函数。然而,三角形永远不会改变它的位置。三角形围绕中心点 (x
, y
) 绘制。
最佳答案
我找到了 official documentation GetAsyncKeyState
有点困惑。我认为 this forum post更好地解释了 GetAsyncKeyState
的工作原理:
GetAsyncKeyState returns a 16-bit signed value. The high bit is set when the current real-time state of the key indicates that it is being held down.
The low bit is set when the key has transitioned from a released to a pressed state (like when the key is first pressed). Though the MSDN documentation indicates this is not reliable.
The value of all other bits should be assumed to be "undefined" and you should discard them. I would not recommend assuming they are 0 because they might not be a in a future version.
That said... you should NOT look for absolute return values. IE: checking for -32767 is wrong. Instead, you should mask out the bit you're interested in:
if(GetAsyncKeyState(x) & 0x8000) { // high bit is set. Key is currently held down. } if(GetAsyncKeyState(x) & 0x0001) { // low bit is set. Key just transitioned from released to pressed. }
因此,此建议与@MikeCAT 在评论中给出的建议相符:您应该使用 GetAsyncKeyState(0x58) & 0x8000
查看是否按下了 X 键。
关于c++ - 如何在 C++ 中读取键盘输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34810421/