Keyboard
(Basics->Input)
キーボードのアルファベットによってピアノの鍵盤のように画面に様々な縞模様が現れます。
アルファベットではないキーが押されたらクリアされます。
キーボードが押されたイベントを取得するkeyPressed()関数内でほとんどの処理が書かれています。
システム変数keyによって現在押されたキーを取得できます。
println(key); としてみると文字が表示されますが、ASCIIコードと呼ばれる文字それぞれに付いた整数(int)を内部で使っています。
ちなみにASCIIコードでは「A」は97、「a」は65です。
/**
* Keyboard.
*
* Click on the image to give it focus and press the letter keys
* to create forms in time and space. Each key has a unique identifying
* number called its ASCII value. These numbers can be used to position
* shapes in space.
*/
int rectWidth;
void setup() {
size(200, 200);
noStroke();
background(0);
rectWidth = width/4;
}
void draw() {
// keep draw() here to continue looping while waiting for keys
// キーボードのイベントを待ってループするだけのdraw()
}
void keyPressed() {
int keyIndex = -1;
//キーボードのA〜Zが押されたときにkyeIndexに0〜25の値が入るように
if (key >= 'A' && key <= 'Z') {
keyIndex = key - 'A'; // このようにするとA-Zを0-25に置きなおせる
//キーボードの小文字のa〜zが押されたときにkyeIndexに0〜25の値が入るように
} else if (key >= 'a' && key <= 'z') {
keyIndex = key - 'a'; // このようにするとa-zを0-25に置きなおせる
}
if (keyIndex == -1) {
// If it's not a letter key, clear the screen
// アルファベットではないキーが押されたら、画面を真っ黒にクリア
background(0);
} else {
// It's a letter key, fill a rectangle
fill(millis() % 255); // ミリ秒を255で割った余り、つまり0-254のどれかのグレーで塗ります
float x = map(keyIndex, 0, 25, 0, width - rectWidth); //map関数を使って0〜25の値を画面幅に合わせてピアノの鍵盤のように割り当てています
rect(x, 0, rectWidth, height);
}
}