Scratch for Java

Stages and the window

The window is what the player sees. The stage is what is shown in it: a backdrop, sprites and texts. A game usually has several stages, such as a title screen, levels and a "game over" screen.

The window

Window window = new Window(480, 360);
window.setStage(new Level());

new Window(480, 360) opens a window 480 pixels wide and 360 high. It is the first thing a program does, in main. There is only one window. Anywhere else, Window.getInstance() gives it to you.

Backdrops

A stage shows a backdrop or a colour:

this.addBackdrop("background");          // a built-in picture
this.addBackdrop("sky", "assets/sky.png"); // your own file, with a name
this.setColor(30, 30, 60);                // red, green, blue from 0 to 255

switchBackdrop("sky"), nextBackdrop() and previousBackdrop() work as in Scratch.

Switching stages

Each stage is a class of its own. setStage switches to another one at once. transitionToStage fades or slides over:

Click the stage, then press space.

  • transitionToStage(new Level(), 1) fades to the new stage in 1 second.
  • transitionToStage(() -> new Title(), Transition.SLIDE_RIGHT, 1) chooses how: SLIDE_LEFT, SLIDE_RIGHT, SLIDE_UP, SLIDE_DOWN, FADE or CROSSFADE. () -> new Title() means "make a new title stage when it is time".
  • new Title() makes a fresh stage. To come back to the same stage as it was, keep it in a variable and pass that instead.

The stage's own scripts

A stage has run() and the when… methods too, like a sprite. Put things there that belong to the whole level: a countdown, spawning enemies, the score.

The camera

A level can be larger than the window. The camera decides which part you see. Use the arrow keys:

getCamera().setPosition(x, y) puts that point in the middle of the window. The UFO always stays in the middle, and the stars move past.

  • getCamera().setZoom(200) shows everything twice as large.
  • Sprites on Layer.UI do not move with the camera. Use it for the score.
  • getMouseX() and getMouseY() already take the camera into account.

Next

  • Time and events: the stage's run() and messages
  • Pixel art and full screen: window sizes and scaling
  • Stage, Window and Camera in the reference
Stages and the window

Create Shareable URL

Select Sections