Skip to main content
GameDev.net gamedev.net
🔒 Locked

handling keyboard input in WndProc

Started by shargath Jun 24, 2012 at 8:37 PM 5 replies 3.6k views
Original Post
shargath
shargath
Hello smile.png , I just jumped into the waters of game developing and I'm making my first 2d game.

So far I've got the window and basic render loop where I'm animating sprite, which is some walking character. Now I want to make the character walking after arrow keyboard buttons input is made...

I have class Character and I thought that it could be storing the current state like "moving to left", "moving to right", etc.

I'm using raw input but I don't know how to set the states of character based on keyboard input, since WndProc doesn't know about instance of object character...

So what's the common way of doing this?
zacaj
zacaj
Personally I have an array of each of the keys

bool keypressed[512]

and when a key is pressed in WndProc I set the appropriate variable in the array to true, and when its released I set it back to false

Then your Character class can just say

if(keypressed['W])
//walk forward

You may have to manually convert non alphanumeric keys to some constant in WndProc ie
#define KEY_UP 257
#define KEY_DOWN 258
I dont remember what the VK_* is for the keys
shargath
shargath
Thank you for your answer zacaj, sound nice and easy but where should be the array's declaration/definition from structural point of view?

I have main.cpp where is APIENTRY WinMain and WndProc and I create the character object before calling ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd);

should I make array as a global and pass to Character's constructor pointer to array?
zacaj
zacaj
Structurally I'd just make it global, since the state of the keyboard is, well, global.

From a future proofing standpoint, if you plan on supporting multiple players, or configurable controls, it would be better to make the Character class have an inputEvent() method that would get sent PLAYER_FORWARD, PLAYER_JUMP type inputs, and then you can map keys to those events for easy controller configuration
shargath
shargath
I just realized what I did wrong, so stupid mistake, bool *pKeyInputHolder is what I have in character.h and then I have it again in constructor so second redefinition erases the first one with different scope variable lifetime
shargath
shargath
Very good article, thank you

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.