Keyboard Input

Here we must again ask

An animation becomes a game when the player can control it. The rendering module gives us IS_KEY_DOWN, which tells us whether a key is being held.

IS_KEY_DOWN

IS_KEY_DOWN takes the name of a key as a string. It returns true if that key is held down right now, and false if not.

csp
You may also type <- !=>= <= for auto complete.

The circle appears while the A key is held, and disappears when it is released.

This is not the same as INPUT. INPUT stops the program and waits for a typed answer. IS_KEY_DOWN never waits. It checks the keyboard at that moment and returns right away, so the animation keeps running.

Click on the page first if nothing happens. The browser only sends key presses to the page that has focus.

Key Names

A key name is the name the browser uses for the key.

keyname
left arrow"ArrowLeft"
right arrow"ArrowRight"
up arrow"ArrowUp"
down arrow"ArrowDown"
letters"a", "w"
digits"1", "2"
space bar"Space"
enter"Enter"

Key names are not case sensitive, so "A" and "a" mean the same key. This is one of the few places in CSP where case does not matter.

The arrow keys and the space bar will not scroll the page while a program is running, so they are safe to use in a game.

Moving a Square

To move something, we check the keys every frame and change its position. We use a velocity variable, vx, and decide what it should be each frame.

csp
You may also type <- !=>= <= for auto complete.

Every frame, vx is reset to 0, so when no key is held the square stops. We use OR so that either the arrow keys or A and D work. If both left and right are held at the same moment, the second IF replaces the first value, and the square goes right.

The variables x, vx, and speed are all created before the loop, as always.

Moving in Four Directions

Nothing stops us from adding a second axis. We use a separate pair of keys for y.

csp
You may also type <- !=>= <= for auto complete.

Pressing up subtracts from y, because y gets smaller as we go up the screen.

Held Versus Pressed

IS_KEY_DOWN is true for every frame that the key is held, not just the first one. That is perfect for walking, but sometimes we want something to happen only once per press, such as firing a shot. To do that, we remember whether the key was down on the previous frame.

csp
You may also type <- !=>= <= for auto complete.

The counter goes up once each time the space bar goes from up to down. Holding it does not keep counting. We check for isDown AND NOT wasDown, which means “down now, but not down last frame.”

Practice


Next: A Very Simple Platformer