2.7 Keyboard Input
Keyboard Control in Greenfoot with isKeyDown
Unit 2: Variables, Decisions, and Input · Lesson 2.7 · about 30 minutes · no coding experience needed
This is the lesson where the game becomes yours to play. It is also where an else if chain, which you just learned to love, becomes exactly the wrong tool.
What you will be able to do
- Move an actor with the arrow keys
- Explain why the key check must live inside act()
- Explain why separate ifs beat a chain for movement keys
Words you will need
- isKeyDown
- In plain words Is this key being held right now?
- More precisely Greenfoot.isKeyDown(String) returns true while the named key is pressed.
Build it step by step
Every step below leaves a scenario that compiles and runs. If you stop halfway you will have something that works, not something broken. Follow along in Greenfoot rather than reading straight through.
-
Step 1
On your screen An actor moving left in the world while the left arrow key is held.
public void act() { if (Greenfoot.isKeyDown("left")) { setLocation(getX() - 3, getY()); } }Compile and run, then hold the left arrow.
Everything here you have already met. `isKeyDown` hands back true or false, which is exactly what an if wants. `setLocation(getX() - 3, getY())` is the line from 1.5: take the current x, subtract 3, leave y alone.
The key name is text in double quotes, and it is lower case: "left", not "Left".
-
Step 2
On your screen The actor responding to all four arrow keys.
public void act() { if (Greenfoot.isKeyDown("left")) { setLocation(getX() - 3, getY()); } if (Greenfoot.isKeyDown("right")) { setLocation(getX() + 3, getY()); } if (Greenfoot.isKeyDown("up")) { setLocation(getX(), getY() - 3); } if (Greenfoot.isKeyDown("down")) { setLocation(getX(), getY() + 3); } }All four directions. Note "up" SUBTRACTS from y, because y grows downward. That is the rule from 1.4 finally paying off.
Look carefully at what these are: four SEPARATE if statements. Not a chain. That is deliberate and it is the next step.
-
Step 3
On your screen A comparison of separate ifs allowing diagonal movement against a chain that does not.
// A CHAIN. Diagonal movement is impossible. if (Greenfoot.isKeyDown("left")) { ... } else if (Greenfoot.isKeyDown("up")) { ... }Here is why the chain is wrong for this job.
A chain stops at the first true condition. Hold left and up together and it handles left, then stops. You can never move diagonally.
Separate ifs are each checked, so both run in the same frame and the actor moves diagonally. This is the clearest example in the course of "which tool" mattering more than "is it correct Java", because both versions compile and run perfectly.
-
Step 4
On your screen The actor stopped at the world edge instead of walking off it.
public void act() { if (Greenfoot.isKeyDown("right") && getX() < getWorld().getWidth() - 1) { setLocation(getX() + 3, getY()); } }And a guard, using && from 2.3: move right only if the right arrow is held AND there is still room.
Greenfoot already clamps an actor inside the world, so this is not strictly needed here. It matters the moment you want your OWN boundary, like a wall part way across, and it shows that a condition can ask about two unrelated things at once.
Mistakes almost everyone makes here
These are the wrong ideas students actually build at this point. Read them even if you think you understand, because a wrong idea you have not noticed is the expensive kind.
Common wrong idea Use an else if chain for the arrow keys.
What is actually true Use separate ifs, or diagonal movement becomes impossible.
Why it matters Both compile and both run. The chain version just quietly cannot do something the player expects.
Common wrong idea isKeyDown remembers that a key was pressed.
What is actually true It reports whether the key is held AT THAT MOMENT, which is why it lives in act().
Why it matters Checking once outside the loop gives a key that works for exactly one frame.
Common wrong idea "up" should increase y.
What is actually true y grows downward, so up SUBTRACTS.
Why it matters The single most common inverted-control bug, straight out of 1.4.
Common wrong idea Key names can be capitalized however you like.
What is actually true They are lower case strings: "left", "right", "up", "down", "space", "a".
Why it matters A wrong key name is not an error. It simply never matches, and the key does nothing.
Check your understanding
Answer these before moving on. They are graded instantly and you can retry.
-
1. Which line moves an actor UP the screen?
-
2. Why must the isKeyDown check be inside act()?
-
3. A player holds left and up together but only moves left. What is the most likely cause?
-
4. What does `Greenfoot.isKeyDown("Left")` do, with a capital L?
-
5. What type does isKeyDown hand back?
Fill in the code
Complete the act() method so the player moves right while the right arrow is held. Use the coordinate form so it works whichever way the actor is facing.
public void act()
{
if (Greenfoot.(""))
{
setLocation(getX() 3, );
}
}
Stuck? Open a hint for each blank
- Blank 1: The method that asks whether a key is held.
- Blank 2: The key name, in lower case, with no quotes needed inside the blank.
- Blank 3: Moving right means x gets bigger.
- Blank 4: y is not changing, so ask the actor for its current y.
Lesson quiz
This one counts toward your progress. Take it when the section above makes sense.
-
1. For four-direction movement including diagonals, you should use:
-
2. isKeyDown returns:
-
3. An actor should move down. Which is right?
-
4. A key does nothing at all and there is no error message. What is worth checking?
-
5. Why does this lesson use setLocation rather than move()?
The short version
- isKeyDown asks whether a key is held right now, so it belongs in act().
- Key names are lower case strings, and a wrong one fails silently.
- Use SEPARATE ifs, not a chain, or diagonal movement is impossible.
- Up is a smaller y. Down is a bigger y.
- setLocation moves by coordinates and ignores facing, which is what arrow keys need.
If you get stuck
These pages cover the problems that come up most often in this lesson. Opening one is not cheating and it is not counted against you.
Get in Touch
Whether you're a student, parent, or teacher — I'd love to hear from you.
Just want free AP CS resources?
Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]