By Waseef Khan & Raghav Jain
New to Java? You can download the slides and source code from Weeks 1–6 of the KCL Tech Academy Java workshops.
On 18 November, we ran Build a Game w/JavaFX #1: World and Movement, the first game development session in our Java workshop series. It was our first time teaching JavaFX, so we tried live coding a 2D sandbox. We got a world on screen and made a player move.
Afterwards, we realised we’d rushed through how the tile grid becomes a picture and what happens between pressing a key and seeing the player move.
Get the workshop starter running
Start with How to Set Up IntelliJ IDEA, Maven and JavaFX to get the game window open. The game code and artwork are in the Workshop 1 files.
When the starter opens, you’ll see a sky, several rows drawn with the grass texture and a player standing still. In this walkthrough, you’ll give the tiles their own textures and connect the keyboard to the player’s movement.
Find the game files
-
src/main/javacontains the game classes. FindSandboxGame.javain theuk.ac.kcltech.sandboxpackage. A package groups related classes and normally matches their folders. -
src/main/resourcesholds the tile and player images. -
src/test/javacontains the tests for the world and the player.
Follow the workshop code
1. Draw one rectangle
Open SandboxGame.java. The class says extends Application to tell Java that it is a kind of JavaFX application. JavaFX calls start(Stage stage) when the app launches. @Override tells the compiler to check that we’re providing the method that Application expects.
Stage: the window └─ Scene: the window's contents └─ StackPane: a layout container └─ Canvas: where we draw A Canvas is a drawing surface. It gives us a GraphicsContext, the object with drawing commands. In render(GraphicsContext g), g is the short name for that object. render means “draw the current game.” It paints the sky first, then the terrain and player, and finally the instructions. A later drawing can cover an earlier one.
Inside render(), find the loops that draw the sky. After those loops and before int firstColumn, add these two lines temporarily.
g.setFill(Color.CORNFLOWERBLUE); g.fillRect(40, 100, 120, 60); setFill chooses the paint for the next filled shape. fillRect(x, y, width, height) draws a rectangle from its top-left corner. On the Canvas, (0, 0) is the top-left of the drawing area, x increases to the right, and y increases downwards. This rectangle starts 40 pixels from the left and 100 from the top, below the instructions. Change 40 to 80 and predict where it will go. Run the game to check, then remove both lines before continuing.
2. Turn numbers in a grid into tiles
Open World.java. A tile is one square of the map. A Tile[][] is an array whose entries are themselves arrays. In this game, each inner array is a row. The world has 20 rows of 80 columns. You can think of the allocation as new Tile[20][80]. Both indexes start at zero, so tiles[16][3] picks the 17th row, then the fourth tile in that row.
Row Col 0 Col 1 Col 2 Col 3 15 AIR AIR AIR AIR 16 GRASS GRASS GRASS GRASS 17 DIRT DIRT DIRT DIRT 18 STONE STONE STONE STONE The constructor fills the grid with two loops. The outer loop picks the row and the inner loop visits each column of that row. Tile is an enum, a type with a fixed list of values. Ours has AIR, GRASS, DIRT, and STONE. The row decides which value every cell in that row gets.
The renderer calls world.get(3, 16) for the cell at tiles[16][3]. The method takes the horizontal coordinate first, so the call reads like (x, y). Inside the method the array still uses row first. World.get() also returns AIR for positions outside the map so drawing code can handle those positions safely.
At this point the grid already contains grass, dirt, and stone. The solid tiles all look like grass because render() uses the same image for each one. Find Image texture = art.grass(); inside the terrain loop and replace just that line with the expression below. Leave the AIR check above it and g.drawImage(...) below it.
Image texture = switch (tile) { case GRASS -> art.grass(); case DIRT -> art.dirt(); case STONE -> art.stone(); case AIR -> throw new IllegalStateException( "Air has no block texture." ); }; A switch expression chooses a value. Here case DIRT -> art.dirt() gives texture the dirt image that GameArt loaded from the resources folder. The continue above the switch skips empty cells, so the sky shows through. The AIR branch reports a mistake if an empty cell somehow reaches the switch. Keep the final }; because the expression is part of the variable declaration. Run again and look for the grass surface, one dirt row, and stone below it.
The grid uses tile positions, but the Canvas uses pixels. With 32-pixel tiles, column 3 starts at x = 3 × 32 = 96, and row 16 starts at y = 16 × 32 = 512. The camera is a horizontal offset. After it scrolls right by 64 pixels, the same tile is still at world x = 96 and is drawn at screen x = 96 − 64 = 32.
3. Remember which keys are held
A key event tells us that a key went down or came up. To keep walking while D is held, we save that state between events. The starter already declares pressed as a Set<KeyCode> backed by a HashSet. A set holds each key only once. Even if JavaFX sends repeat events for a held key, there is still just one D in the set.
In SandboxGame.start(), add these handlers just after the line that creates the Scene. The event -> { ... } syntax is a lambda. It gives JavaFX a block of code to call later, when the event happens. event.getCode() tells us which key it was.
scene.setOnKeyPressed(event -> { KeyCode key = event.getCode(); pressed.add(key); System.out.println("Pressed: " + key); }); scene.setOnKeyReleased(event -> { KeyCode key = event.getCode(); pressed.remove(key); System.out.println("Released: " + key); }); Run the game, click its window to give it keyboard focus, then press and release D. Look for Pressed: D and Released: D in IntelliJ’s Run panel. The player stands still because we’ve only recorded the input so far. Once the messages are working, you can remove the two println lines. The starter also clears the set when the window loses focus, so switching windows won’t leave a key stuck.
4. Work out how far the player should move
Player stores x and y, the character’s position in the world. This lesson changes x and leaves y fixed, so the character walks along the ground. In Player.update(), replace just double dx = 0; with the following. Leave the existing code below that updates facing and limits the position to the map.
int direction = 0; if (right) direction += 1; if (left) direction -= 1; double dx = direction * MOVE_SPEED * dt; The two if statements are separate on purpose. Pressing both directions adds 1 and subtracts 1, leaving zero. dx is the change in horizontal position. The calculation is direction × speed × time. For example, walking right at 210 pixels per second for 0.016 seconds gives +1 × 210 × 0.016 = 3.36 pixels. Using elapsed time lets the player cover about the same distance per second even when the game redraws more often. A positive dx moves right, a negative dx moves left, and zero keeps the previous facing direction. The code below adds dx to x and limits the position so the whole character stays inside the map.
In the Maven tool window, double-click Lifecycle → test. A test calls a method with known inputs and checks the result. Here the tests call the world and player code directly, so you can check movement without a game window or keyboard. Expect six passing tests after this step. Movement tests can fail on the untouched starter because dx is still zero.
5. Connect the keyboard to each frame
In SandboxGame.java, find private void update(double dt). The starter has two key checks commented out just above boolean left = false; and boolean right = false;. Remove the leading // from both checks and delete the two false declarations. The checks should sit directly above the existing player.update(dt, left, right); call.
boolean left = pressed.contains(KeyCode.A) || pressed.contains(KeyCode.LEFT); boolean right = pressed.contains(KeyCode.D) || pressed.contains(KeyCode.RIGHT); player.update(dt, left, right); pressed.contains(KeyCode.D) asks whether D is currently held. It gives us a boolean, either true or false. The || operator means or, so holding D or Right Arrow makes right true. A and Left Arrow do the same for left. The last line passes both answers and the elapsed time dt to Player.update(), which calculates how far to move.
| Keys | left | right | Direction |
|---|---|---|---|
| None | false | false | 0 |
| A or Left | true | false | −1 |
| D or Right | false | true | +1 |
| Both ways | true | true | 0 |
A frame is one picture the game draws. JavaFX’s AnimationTimer already calls handle(now) each frame. On the first call, the starter stores the current time and returns because there is no earlier frame to measure. After that, now - lastFrame gives elapsed nanoseconds. Dividing by one billion gives seconds, which we store as dt. The cap of 0.033 seconds (33 milliseconds) limits the distance the player can move in a single frame after a long pause.
In handle(now), find the standalone lastFrame = now; that comes after the line calculating dt. Add update(dt); there, just before the existing render call.
double dt = Math.min( (now - lastFrame) / 1_000_000_000.0, 0.033 ); lastFrame = now; update(dt); render(graphics); First the game updates the player and camera using the keys that are held, then it draws the new positions. Run the game again, click the window, and try A, D, and the arrow keys. Releasing all keys or holding opposite directions should stop the player. If the Run panel reports the keys but the player stays still, check both direction flags and the timer call.
Where to look when you want to change something
-
SandboxGameopens the window, handles input, and draws each frame. -
Worldstores the tile grid and answers tile lookups. -
Playerkeeps track of the character’s position and movement. -
GameArtloads and reuses the artwork. -
GameConfigstores shared values such as tile size and movement speed. Try changing the speed, then predict which part of the distance calculation changes.
