PathEngine home previous: Generating shape preprocessnext: Getting the position under the mouse
Contents, Programmers Guide, Example Projects, Tutorials, Tutorial 1, The update loop ‑ handling key messages

The update loop - handling key messages

The 'basicapplication' tutorial we used the following while loop as a main loop.

while(!testbed->getKeyState("_ESCAPE"))
{
	//...
}

This makes a test once a frame for whether the escape key is currently down, and if so exits the application.
The problem with this approach is that if the escape key is pressed and released during a single frame then it will not be detected.
A better way to use the keyboard as a control mechanism is by receiving key messages.

The iTestBed::receiveKeyMessage() function provides access to a buffer of messages for key events that took place since the previous frame. (Since the previous call to update().)
While there are messages remaining, this function a pointer to a string for the next message, and removes that message from the buffer.
When no messages remain, a null pointer is returned.

The strings used to represents the keys relating to an event are the same as for getKeyState().
See Key Strings for a list.
Key down events are preprended by 'd' and key up events are preprended by 'u'.

We can process all messages received since last frame with the following code:

const char *keypressed;
while(keypressed=testbed->receiveKeyMessage())
{
	if(keypressed[0]!='d') // is it a key down message?
		continue;

	//.. the string at keypressed+1 tells us what key was pressed
	//.. so perform any action corresponding to this key press
}

Some keys are represented by a single characters whereas others are represented by a string.
All key strings of more than one character start with '_' so we can use a case statement that switches on the first character of the string.

We want to exit if escape is pressed, place or move the agent if '4' is pressed, place or move the obstruction 1 if '5' is pressed, and place or move the obstruction 2 if '6' is pressed.
So our case statement looks like this:

switch(keypressed[1])
{
case '_':
	{
		if(strcmp("ESCAPE",keypressed+2)==0)
			exitflag=true;
		break;
	}
case '4':
	//.. code to place or move the agent
	break;
case '5':
	//.. code to place or move obstruction 1
	break;
case '6':
	//.. code to place or move obstruction 2
	break;
}

Documentation for PathEngine release 6.04 - Copyright © 2002-2024 PathEnginenext: Getting the position under the mouse