JavaScratch Sprite API
Every method you can call from a sprite's Java code, grouped like Scratch's block categories, with an example for each.
How sprite code works
In JavaScratch every sprite (and the stage) is programmed in Java instead of blocks. The code you type in the
Scripts tab is the inside of a Java class that extends SpriteScript, so you write
fields (variables) and methods. You can call every method in this reference directly — no
this. or object needed.
Event methods are the hat blocks. A method called whenFlagClicked() runs when the green flag is
clicked, whenKeyPressed(String key) when a key is pressed, and so on. Every event method runs in its own
thread, at the same time as the others — exactly like separate scripts in Scratch.
int score = 0; // a field: a variable for this sprite only
public void whenFlagClicked() { // when green flag clicked
goTo(0, 0);
say("Hello!", 2);
forever(() -> { // forever (one repetition per frame)
move(5);
ifOnEdgeBounce();
});
}
public void whenClicked() { // when this sprite clicked
score++;
playSound("pop");
}
Loops and frames
forever, repeat and repeatUntil wait one frame (1/30 second) after each
repetition, so you can see the animation. In your own Java while / for loops, call
nextFrame(). Inside the () -> { } lambdas you can change fields but not local
variables, so keep counters and scores in fields.
Coordinates and directions
The stage is 480 × 360 pixels. x goes from -240 (left) to 240 (right) and y from -180 (bottom) to 180 (top); (0, 0) is the centre. Direction 90 points right, 0 up, -90 left and 180 down.
Reading this reference
- Each method shows its Java signature, whether it works for Sprites only or Sprites & Stage, the matching Scratch block, its parameters and an example.
- Every example is complete sprite code: paste it into a sprite's Scripts tab and click the green flag.
- Examples use the names of the built-in sprites (Bean, Ball, Apple, Star…), sounds (“pop”) and backdrops (“blue sky”, “night”) — rename them to match your project.
- Costume, backdrop and letter numbers start at 1, like in Scratch.
Categories
Quick reference
| Category | Method | What it does | Use in |
|---|---|---|---|
| Motion | void move(double steps) | Moves the sprite forward in the direction it is pointing. | sprite |
| Motion | void turnRight(double degrees) | Turns the sprite clockwise. | sprite |
| Motion | void turnLeft(double degrees) | Turns the sprite anticlockwise. | sprite |
| Motion | void pointInDirection(double degrees) | Points the sprite in a direction: 90 = right, 0 = up, -90 = left, 180 = down. | sprite |
| Motion | void pointTowards(String target) | Points the sprite towards the mouse pointer or towards another sprite. | sprite |
| Motion | void goTo(double x, double y) | Jumps straight to a position on the stage. | sprite |
| Motion | void goTo(String target) | Jumps to the mouse pointer, a random position or another sprite. | sprite |
| Motion | void glide(double seconds, double x, double y) | Moves smoothly to a position over a number of seconds. | sprite |
| Motion | void changeXBy(double dx) | Moves the sprite right (positive) or left (negative). | sprite |
| Motion | void setX(double x) | Sets the x position, keeping y the same. | sprite |
| Motion | void changeYBy(double dy) | Moves the sprite up (positive) or down (negative). | sprite |
| Motion | void setY(double y) | Sets the y position, keeping x the same. | sprite |
| Motion | void ifOnEdgeBounce() | If the sprite is touching the edge of the stage, it turns around (like a ball bouncing off a wall) and moves back onto the stage. | sprite |
| Motion | void setRotationStyle(String style) | Chooses how the costume turns when the direction changes. | sprite |
| Motion | double getX() | Reports the sprite's x position. | sprite |
| Motion | double getY() | Reports the sprite's y position. | sprite |
| Motion | double getDirection() | Reports the direction the sprite points in. | sprite |
| Looks | void say(Object message) | Shows a speech bubble that stays until the sprite says something else. | sprite |
| Looks | void say(Object message, double seconds) | Shows a speech bubble for some seconds, then removes it. | sprite |
| Looks | void think(Object message) | Shows a thought bubble (with little circles instead of a pointer). | sprite |
| Looks | void think(Object message, double seconds) | Shows a thought bubble for some seconds. | sprite |
| Looks | void show() | Makes the sprite visible. | sprite |
| Looks | void hide() | Makes the sprite invisible. | sprite |
| Looks | boolean isVisible() | Tells whether the sprite is currently shown. | sprite |
| Looks | void switchCostumeTo(String name) | Switches to the costume with that name (see the Costumes tab). | sprite |
| Looks | void switchCostumeTo(int number) | Switches to a costume by number. | sprite |
| Looks | void nextCostume() | Switches to the next costume (back to the first after the last). | sprite |
| Looks | int getCostumeNumber() | Reports the current costume number. | sprite |
| Looks | String getCostumeName() | Reports the current costume's name. | sprite |
| Looks | void switchBackdropTo(String name) | Switches the stage's backdrop by name. | all |
| Looks | void switchBackdropTo(int number) | Switches the backdrop by number (starting at 1). | all |
| Looks | void nextBackdrop() | Switches to the next backdrop. | all |
| Looks | String backdropName() | Reports the backdrop name. | all |
| Looks | int backdropNumber() | Reports the backdrop number. | all |
| Looks | void setEffect(String effect, double value) | Sets a graphic effect. | all |
| Looks | void changeEffect(String effect, double by) | Changes a graphic effect by an amount. | all |
| Looks | void clearGraphicEffects() | Removes all graphic effects. | all |
| Looks | void changeSizeBy(double percent) | Grows (positive) or shrinks (negative) the sprite. | sprite |
| Looks | void setSizeTo(double percent) | Sets the size in percent of the costume's normal size (100 = normal). | sprite |
| Looks | double getSize() | Reports the size. | sprite |
| Looks | void goToFront() | Draws this sprite in front of all other sprites. | sprite |
| Looks | void goToBack() | Draws this sprite behind all other sprites (but in front of the backdrop). | sprite |
| Looks | void goBackLayers(int n) | Moves the sprite back by some layers. | sprite |
| Looks | void goForwardLayers(int n) | Moves the sprite forward by some layers. | sprite |
| Sound | void playSound(String name) | Starts playing a sound from the sprite's Sounds tab and continues immediately. | all |
| Sound | void playSoundUntilDone(String name) | Plays a sound and waits until it has finished. | all |
| Sound | void stopAllSounds() | Stops every sound that is playing. | all |
| Sound | void playNote(double note, double beats) | Plays a MIDI note for some beats and waits. | all |
| Sound | void playDrum(int drum, double beats) | Plays a drum sound for some beats. | all |
| Sound | void rest(double beats) | Waits for some beats (a musical pause). | all |
| Sound | void setInstrument(int instrument) | Chooses the General MIDI instrument used by playNote: 1 piano, 13 marimba, 25 nylon guitar, 33 bass, 41 violin, 57 trumpet, 66 saxophone, 74 flute, 81 synth lead …. | all |
| Sound | void setTempo(double bpm) | Sets the tempo in beats per minute (shared by all sprites). | all |
| Sound | void changeTempo(double by) | Changes the tempo. | all |
| Sound | double tempo() | Reports the tempo. | all |
| Sound | void setVolume(double percent) | Sets this sprite's volume, 0–100 %. | all |
| Sound | void changeVolume(double by) | Changes the volume. | all |
| Sound | double volume() | Reports the volume. | all |
| Pen | void penDown() | Puts the pen down: from now on the sprite draws a line as it moves. | sprite |
| Pen | void penUp() | Lifts the pen: the sprite stops drawing. | sprite |
| Pen | void clearPen() | Erases all pen lines and stamps from the stage. | all |
| Pen | void stamp() | Prints a picture of the sprite onto the stage, like a rubber stamp. | sprite |
| Pen | void setPenColor(Color color) | Sets the pen colour. | sprite |
| Pen | void setPenHue(double hue) | Sets the pen colour as a number like Scratch 2: 0 red, 35 yellow, 70 green, 130 blue, 170 purple, 200 red again. | sprite |
| Pen | void changePenHue(double by) | Shifts the pen colour around the rainbow. | sprite |
| Pen | void setPenSize(double size) | Sets the pen thickness in pixels. | sprite |
| Pen | void changePenSize(double by) | Makes the pen thicker or thinner. | sprite |
| Variables | fields: int score = 0; | A variable “for this sprite only” is simply a Java field: declare it outside any method. | all |
| Variables | void setVariable(String name, Object value) | Sets a global variable that every sprite and the stage can read. | all |
| Variables | void changeVariable(String name, double by) | Adds a number to a global variable (a variable that doesn't exist yet starts at 0). | all |
| Variables | Object getVariable(String name) | Reads a global variable. | all |
| Variables | double getNumber(String name) | Reads a global variable as a number (text that isn't a number gives 0). | all |
| Variables | void showVariable(String name) | Shows a monitor for a global variable at the top-left of the stage. | all |
| Variables | void hideVariable(String name) | Hides a variable monitor. | all |
| Variables | void watch(String label, Supplier<Object> value) | Shows a monitor for any value — for example one of your fields. | all |
| Variables | void unwatch(String label) | Removes a monitor created with watch() or showVariable(). | all |
| Events | void whenFlagClicked() | Runs when the green flag is clicked (or F5 / Ctrl+Enter). | all |
| Events | void whenKeyPressed(String key) | Runs when any key is pressed. | all |
| Events | void whenClicked() | Runs when this sprite is clicked (on the stage: when the stage is clicked). | all |
| Events | void whenIReceive(String message) | Runs when any message is broadcast with broadcast() or broadcastAndWait(). | all |
| Events | void whenBackdropSwitchesTo(String backdrop) | Runs when the stage switches backdrop. | all |
| Events | @WhenFlagClicked @WhenKeyPressed("key") @WhenThisSpriteClicked @WhenIReceive("message") @WhenIStartAsClone @WhenBackdropSwitchesTo("name") | Annotations let a method with any name react to an event — and let one sprite have several scripts for the same event, like several hat blocks in Scratch. | all |
| Events | void broadcast(String message) | Sends a message to every sprite and the stage, starting their whenIReceive methods. | all |
| Events | void broadcastAndWait(String message) | Sends a message and waits until every script started by it has finished. | all |
| Control | void waitSeconds(double seconds) | Pauses this script for some seconds. | all |
| Control | void forever(Runnable body) | Repeats the body forever, waiting one frame (1/30 s) after each repetition. | all |
| Control | void repeat(int times, Runnable body) | Repeats the body a number of times, one repetition per frame. | all |
| Control | void repeatUntil(BooleanSupplier condition, Runnable body) | Repeats the body until the condition becomes true. | all |
| Control | void waitUntil(BooleanSupplier condition) | Waits until the condition becomes true. | all |
| Control | void nextFrame() | Waits until the next screen refresh (1/30 s). | all |
| Control | if / else | Plain Java if-statements work like Scratch's if and if-else blocks. | all |
| Control | void stopAll() | Stops every script of every sprite, like the red stop sign. | all |
| Control | void stopThisScript() | Stops the method (script) that is running this line. | all |
| Control | void stopOtherScriptsInSprite() | Stops all other running methods of this sprite. | all |
| Control | void whenIStartAsClone() | Event method: runs in a new clone right after createClone(). | sprite |
| Control | void createClone() | Creates a copy of this sprite (position, costume, size, effects and field values are copied). | sprite |
| Control | void createCloneOf(String spriteName) | Creates a clone of another sprite (or of this sprite with "myself"). | all |
| Control | void deleteThisClone() | Deletes this clone and stops its scripts. | sprite |
| Control | boolean isClone() | Tells whether this is a clone. | sprite |
| Sensing | boolean isTouching(String what) | Checks pixel-perfectly whether the sprite touches the edge of the stage, the mouse pointer or another sprite (including that sprite's clones). | sprite |
| Sensing | boolean isTouchingColor(Color color) | Checks whether the sprite touches a colour drawn on the stage (backdrop, pen lines or other sprites). | sprite |
| Sensing | double distanceTo(String target) | Reports the distance to the mouse pointer or to another sprite. | sprite |
| Sensing | String ask(Object question) | Shows the question (as a speech bubble for a visible sprite) and an input box under the stage, and waits until the user presses Enter. | all |
| Sensing | String answer() | Reports the most recent answer to ask(). | all |
| Sensing | boolean isKeyPressed(String key) | Checks whether a key is held down right now. | all |
| Sensing | boolean isMouseDown() | Checks whether the mouse button is down. | all |
| Sensing | double mouseX() | Reports the mouse x position. | all |
| Sensing | double mouseY() | Reports the mouse y position. | all |
| Sensing | double timer() | Reports the timer in seconds. | all |
| Sensing | void resetTimer() | Sets the timer back to 0. | all |
| Sensing | double xPositionOf(String sprite) | Reports another sprite's x position. | all |
| Sensing | double yPositionOf(String sprite) | Reports another sprite's y position. | all |
| Sensing | double directionOf(String sprite) | Reports another sprite's direction. | all |
| Sensing | int costumeNumberOf(String sprite) | Reports another sprite's costume number. | all |
| Sensing | void setDraggable(boolean draggable) | Lets the user drag the sprite with the mouse in full-screen mode (in the editor every sprite can be dragged). | sprite |
| Operators | int pickRandom(int from, int to) | Picks a random whole number. | all |
| Operators | double pickRandom(double from, double to) | Picks a random decimal number. | all |
| Operators | String join(Object... parts) | Joins any number of values into one text. | all |
| Operators | String letterOf(int index, String text) | Reports a letter of a text. | all |
| Operators | String str(Object value) | Turns any value into text, formatted like Scratch (10.0 → "10"). | all |
| Operators | double toNumber(Object value) | Turns text (or anything) into a number, like Scratch does. | all |
| Operators | Java operators and Math | All of Java is available: + - * / % for arithmetic, < > <= >= == != to compare numbers, && (and), || (or), ! (not), text.equals(…) to compare text, and Math.round, Math.abs, Math.sqrt, Math.floor, Math.sin, Math.pow …. | all |
| More & Output | custom methods (Scratch's “Make a Block”) | Write your own methods and call them from your event methods. | all |
| More & Output | void print(Object value) | Writes a line to the Output panel below the editor, prefixed with the sprite's name. | all |
| More & Output | String getName() | Reports the sprite's name (clones have the same name). | all |