Scratch for Java

Sprite::whenKeyPressed(keyCode)

This method is called when a key is pressed. The method will receive the key code as a paramter.

Examples

import org.openpatch.scratch.KeyCode;
import org.openpatch.scratch.Sprite;
import org.openpatch.scratch.Stage;
import org.openpatch.scratch.Window;

public class SpriteWhenKeyPressed {

  class CustomSprite extends Sprite {

    public CustomSprite() {
      this.addCostume("zeta", "assets/zeta_green_badge.png");
      this.addCostume("gamma", "assets/gamma_purple_badge.png");
    }

    @Override
    public void whenKeyPressed(int keyCode) {
      if (keyCode == KeyCode.VK_UP) {
        this.changeY(-2);
      } else if (keyCode == KeyCode.VK_DOWN) {
        this.changeY(2);
      } else if (keyCode == KeyCode.VK_LEFT) {
        this.changeX(-2);
      } else if (keyCode == KeyCode.VK_RIGHT) {
        this.changeX(2);
      }
    }
  }

  public SpriteWhenKeyPressed() {
    Stage myStage = new Stage(254, 100);
    myStage.add(new CustomSprite());
    while (myStage.getTimer().forMillis(3000))
      ;
    Window.getInstance().exit();
  }

  public static void main(String[] args) {
    new SpriteWhenKeyPressed();
  }
}

View on GitHub

Syntax

Java

void whenKeyPressed(keyCode)

Scratch

Parameters

NameData TypeDescription
keyCodeintA key code. You can use the enum KeyCode. For example KeyCode.VK_SPACE.

Return

void