JavaScratch Sprite API

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

x: -240x: 240 y: 180y: -180(0, 0) 90 0 -90 180

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

CategoryMethodWhat it doesUse in
Motionvoid move(double steps)Moves the sprite forward in the direction it is pointing.sprite
Motionvoid turnRight(double degrees)Turns the sprite clockwise.sprite
Motionvoid turnLeft(double degrees)Turns the sprite anticlockwise.sprite
Motionvoid pointInDirection(double degrees)Points the sprite in a direction: 90 = right, 0 = up, -90 = left, 180 = down.sprite
Motionvoid pointTowards(String target)Points the sprite towards the mouse pointer or towards another sprite.sprite
Motionvoid goTo(double x, double y)Jumps straight to a position on the stage.sprite
Motionvoid goTo(String target)Jumps to the mouse pointer, a random position or another sprite.sprite
Motionvoid glide(double seconds, double x, double y)Moves smoothly to a position over a number of seconds.sprite
Motionvoid changeXBy(double dx)Moves the sprite right (positive) or left (negative).sprite
Motionvoid setX(double x)Sets the x position, keeping y the same.sprite
Motionvoid changeYBy(double dy)Moves the sprite up (positive) or down (negative).sprite
Motionvoid setY(double y)Sets the y position, keeping x the same.sprite
Motionvoid 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
Motionvoid setRotationStyle(String style)Chooses how the costume turns when the direction changes.sprite
Motiondouble getX()Reports the sprite's x position.sprite
Motiondouble getY()Reports the sprite's y position.sprite
Motiondouble getDirection()Reports the direction the sprite points in.sprite
Looksvoid say(Object message)Shows a speech bubble that stays until the sprite says something else.sprite
Looksvoid say(Object message, double seconds)Shows a speech bubble for some seconds, then removes it.sprite
Looksvoid think(Object message)Shows a thought bubble (with little circles instead of a pointer).sprite
Looksvoid think(Object message, double seconds)Shows a thought bubble for some seconds.sprite
Looksvoid show()Makes the sprite visible.sprite
Looksvoid hide()Makes the sprite invisible.sprite
Looksboolean isVisible()Tells whether the sprite is currently shown.sprite
Looksvoid switchCostumeTo(String name)Switches to the costume with that name (see the Costumes tab).sprite
Looksvoid switchCostumeTo(int number)Switches to a costume by number.sprite
Looksvoid nextCostume()Switches to the next costume (back to the first after the last).sprite
Looksint getCostumeNumber()Reports the current costume number.sprite
LooksString getCostumeName()Reports the current costume's name.sprite
Looksvoid switchBackdropTo(String name)Switches the stage's backdrop by name.all
Looksvoid switchBackdropTo(int number)Switches the backdrop by number (starting at 1).all
Looksvoid nextBackdrop()Switches to the next backdrop.all
LooksString backdropName()Reports the backdrop name.all
Looksint backdropNumber()Reports the backdrop number.all
Looksvoid setEffect(String effect, double value)Sets a graphic effect.all
Looksvoid changeEffect(String effect, double by)Changes a graphic effect by an amount.all
Looksvoid clearGraphicEffects()Removes all graphic effects.all
Looksvoid changeSizeBy(double percent)Grows (positive) or shrinks (negative) the sprite.sprite
Looksvoid setSizeTo(double percent)Sets the size in percent of the costume's normal size (100 = normal).sprite
Looksdouble getSize()Reports the size.sprite
Looksvoid goToFront()Draws this sprite in front of all other sprites.sprite
Looksvoid goToBack()Draws this sprite behind all other sprites (but in front of the backdrop).sprite
Looksvoid goBackLayers(int n)Moves the sprite back by some layers.sprite
Looksvoid goForwardLayers(int n)Moves the sprite forward by some layers.sprite
Soundvoid playSound(String name)Starts playing a sound from the sprite's Sounds tab and continues immediately.all
Soundvoid playSoundUntilDone(String name)Plays a sound and waits until it has finished.all
Soundvoid stopAllSounds()Stops every sound that is playing.all
Soundvoid playNote(double note, double beats)Plays a MIDI note for some beats and waits.all
Soundvoid playDrum(int drum, double beats)Plays a drum sound for some beats.all
Soundvoid rest(double beats)Waits for some beats (a musical pause).all
Soundvoid 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
Soundvoid setTempo(double bpm)Sets the tempo in beats per minute (shared by all sprites).all
Soundvoid changeTempo(double by)Changes the tempo.all
Sounddouble tempo()Reports the tempo.all
Soundvoid setVolume(double percent)Sets this sprite's volume, 0–100 %.all
Soundvoid changeVolume(double by)Changes the volume.all
Sounddouble volume()Reports the volume.all
Penvoid penDown()Puts the pen down: from now on the sprite draws a line as it moves.sprite
Penvoid penUp()Lifts the pen: the sprite stops drawing.sprite
Penvoid clearPen()Erases all pen lines and stamps from the stage.all
Penvoid stamp()Prints a picture of the sprite onto the stage, like a rubber stamp.sprite
Penvoid setPenColor(Color color)Sets the pen colour.sprite
Penvoid 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
Penvoid changePenHue(double by)Shifts the pen colour around the rainbow.sprite
Penvoid setPenSize(double size)Sets the pen thickness in pixels.sprite
Penvoid changePenSize(double by)Makes the pen thicker or thinner.sprite
Variablesfields: int score = 0;A variable “for this sprite only” is simply a Java field: declare it outside any method.all
Variablesvoid setVariable(String name, Object value)Sets a global variable that every sprite and the stage can read.all
Variablesvoid changeVariable(String name, double by)Adds a number to a global variable (a variable that doesn't exist yet starts at 0).all
VariablesObject getVariable(String name)Reads a global variable.all
Variablesdouble getNumber(String name)Reads a global variable as a number (text that isn't a number gives 0).all
Variablesvoid showVariable(String name)Shows a monitor for a global variable at the top-left of the stage.all
Variablesvoid hideVariable(String name)Hides a variable monitor.all
Variablesvoid watch(String label, Supplier<Object> value)Shows a monitor for any value — for example one of your fields.all
Variablesvoid unwatch(String label)Removes a monitor created with watch() or showVariable().all
Eventsvoid whenFlagClicked()Runs when the green flag is clicked (or F5 / Ctrl+Enter).all
Eventsvoid whenKeyPressed(String key)Runs when any key is pressed.all
Eventsvoid whenClicked()Runs when this sprite is clicked (on the stage: when the stage is clicked).all
Eventsvoid whenIReceive(String message)Runs when any message is broadcast with broadcast() or broadcastAndWait().all
Eventsvoid 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
Eventsvoid broadcast(String message)Sends a message to every sprite and the stage, starting their whenIReceive methods.all
Eventsvoid broadcastAndWait(String message)Sends a message and waits until every script started by it has finished.all
Controlvoid waitSeconds(double seconds)Pauses this script for some seconds.all
Controlvoid forever(Runnable body)Repeats the body forever, waiting one frame (1/30 s) after each repetition.all
Controlvoid repeat(int times, Runnable body)Repeats the body a number of times, one repetition per frame.all
Controlvoid repeatUntil(BooleanSupplier condition, Runnable body)Repeats the body until the condition becomes true.all
Controlvoid waitUntil(BooleanSupplier condition)Waits until the condition becomes true.all
Controlvoid nextFrame()Waits until the next screen refresh (1/30 s).all
Controlif / elsePlain Java if-statements work like Scratch's if and if-else blocks.all
Controlvoid stopAll()Stops every script of every sprite, like the red stop sign.all
Controlvoid stopThisScript()Stops the method (script) that is running this line.all
Controlvoid stopOtherScriptsInSprite()Stops all other running methods of this sprite.all
Controlvoid whenIStartAsClone()Event method: runs in a new clone right after createClone().sprite
Controlvoid createClone()Creates a copy of this sprite (position, costume, size, effects and field values are copied).sprite
Controlvoid createCloneOf(String spriteName)Creates a clone of another sprite (or of this sprite with "myself").all
Controlvoid deleteThisClone()Deletes this clone and stops its scripts.sprite
Controlboolean isClone()Tells whether this is a clone.sprite
Sensingboolean 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
Sensingboolean isTouchingColor(Color color)Checks whether the sprite touches a colour drawn on the stage (backdrop, pen lines or other sprites).sprite
Sensingdouble distanceTo(String target)Reports the distance to the mouse pointer or to another sprite.sprite
SensingString 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
SensingString answer()Reports the most recent answer to ask().all
Sensingboolean isKeyPressed(String key)Checks whether a key is held down right now.all
Sensingboolean isMouseDown()Checks whether the mouse button is down.all
Sensingdouble mouseX()Reports the mouse x position.all
Sensingdouble mouseY()Reports the mouse y position.all
Sensingdouble timer()Reports the timer in seconds.all
Sensingvoid resetTimer()Sets the timer back to 0.all
Sensingdouble xPositionOf(String sprite)Reports another sprite's x position.all
Sensingdouble yPositionOf(String sprite)Reports another sprite's y position.all
Sensingdouble directionOf(String sprite)Reports another sprite's direction.all
Sensingint costumeNumberOf(String sprite)Reports another sprite's costume number.all
Sensingvoid 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
Operatorsint pickRandom(int from, int to)Picks a random whole number.all
Operatorsdouble pickRandom(double from, double to)Picks a random decimal number.all
OperatorsString join(Object... parts)Joins any number of values into one text.all
OperatorsString letterOf(int index, String text)Reports a letter of a text.all
OperatorsString str(Object value)Turns any value into text, formatted like Scratch (10.0 → "10").all
Operatorsdouble toNumber(Object value)Turns text (or anything) into a number, like Scratch does.all
OperatorsJava operators and MathAll 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 & Outputcustom methods (Scratch's “Make a Block”)Write your own methods and call them from your event methods.all
More & Outputvoid print(Object value)Writes a line to the Output panel below the editor, prefixed with the sprite's name.all
More & OutputString getName()Reports the sprite's name (clones have the same name).all