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_UP) {
        this.changeY(20);
      } else if (keyCode == KeyCode.VK_DOWN) {
        this.changeY(-20);
      } else if (keyCode == KeyCode.VK_LEFT) {
        this.changeX(-20);
      } else if (keyCode == KeyCode.VK_RIGHT) {
        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

when [name v] key pressed

Parameters

Name Data Type Description
keyCode int A key code. You can use the enum KeyCode. For example KeyCode.VK_SPACE.

Return

void

whenKeyPressed(keyCode)