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;

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_W) {
        this.changeY(20);
      } else if (keyCode == KeyCode.VK_S) {
        this.changeY(-20);
      } else if (keyCode == KeyCode.VK_A) {
        this.changeX(-20);
      } else if (keyCode == KeyCode.VK_D) {
        this.changeX(20);
      }
    }
  }

  public SpriteWhenKeyPressed() {
    Stage myStage = new Stage(600, 240);
    myStage.add(new CustomSprite());
    while (myStage.getTimer().forMillis(3000))
      ;
    myStage.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