This uses keyPressed() and keyReleased() to capture the user interface events that occur when the user presses and releases a key on the keyboard. When that happens, the functions capture the key's character and character code. Getting the code, with keyCode gives a unique integer for every key on the keyboard. We want to use the right and left arrow keys, which give back 37 and 39 respectively.
Using the keyPressed() and keyReleased() events is more reliable than testing for them in the draw() loop with if (keyPressed) { //stuff }.
The general format for getting the keyPressed() and keyReleased() events is to put the value of what the key was into a global variable, like this:
keyCode within the context of keyPressed() and keyReleased() gives the key code integer of the key that was pressed or release.
PROCESSING
Simple Key Control
// Simple Key Keyboard Control
// Left, Right arrow for motion
// Variable for the size of robot
// (required for passing edges of window)
int robotWidth = 100;
int robotHeight = 100;
// Robot movement variables
float robotSpeed = 2.5; // Speed of movement
float newX = 200; // Center robot at start
float changeX = 0; // How much to change the X location
// keyPressed Variables
int whichKeyUp; // Variable to hold key released
int whichKeyDown; // Variable to hold key pressed
void setup() {
size(500, 500);
}
void draw() {
background(128);
// ----------------------------------------------------
// Check the Keys
// keyCodes: left 37, right 39
// LEFT 37
if (whichKeyDown == 37) {
changeX = -robotSpeed;
}
if (whichKeyUp == 37) {
changeX = 0;
whichKeyUp = 0;
whichKeyDown = 0;
}
// RIGHT 39
if (whichKeyDown == 39) {
changeX = robotSpeed;
}
if (whichKeyUp == 39) {
changeX = 0;
whichKeyUp = 0;
whichKeyDown = 0;
}
// ----------------------------------------------------
// ROBOT
// Wrap robot
if (newX > width) {newX = -robotWidth; }
if (newX < -robotWidth) { newX = width; }
newX += changeX;
// Move robot
translate(newX, 200);
// Draw robot
drawRobot();
}
// ------------------------------------------------------
// Draw Robot Function
void drawRobot() {
ellipseMode(CORNER);
fill(255);
ellipse(0, 0, robotWidth, robotHeight);
}
// ------------------------------------------------------
// Get key pressed and released events
void keyPressed() {
whichKeyDown = keyCode;
}
void keyReleased() {
whichKeyUp = keyCode;
}