Example app
Follow the mouse
An ordinary Player object follows a target.
Run this example
Stop the app and save your current Main and helpers outside src/. Copy the files shown below into the listed destinations in your standalone starter, creating resource folders when needed. Replace Main and the listed helpers. Keep the zero/ framework folder and build files. If an older downloaded kit does not have these examples, use the source shown here.
- examples/animation/Main.java →
src/main/java/Main.java - examples/animation/Player.java →
src/main/java/Player.java
Run App to rebuild. Click the canvas before testing input. These examples run in VS Code, in a separate JavaFX window.
Open related lessonRead the source
animation/Main.java
import javafx.scene.input.KeyCode;
import javafx.scene.paint.Color;
import zero.SketchApp;
/** Start here: ordinary Java fields, methods, and objects. */
public class Main extends SketchApp {
private Player player;
@Override
public void settings() {
size(800, 500);
title("My Zero App");
}
@Override
public void setup() {
player = new Player(width() / 2, height() / 2);
}
@Override
public void update(double seconds) {
// You decide which objects update and what information they need.
if (keyDown(KeyCode.SPACE)) {
player.update(width() / 2, height() / 2, seconds);
} else {
player.update(mouseX(), mouseY(), seconds);
}
}
@Override
public void draw() {
background(Color.web("#f4f7fc"));
fill(Color.web("#233247"));
textSize(20);
text("Move your mouse. Hold Space to pull toward the centre.", 24, 36);
player.draw(this);
}
public static void main(String[] args) {
launch(args);
}
}
animation/Player.java
import javafx.scene.paint.Color;
import zero.SketchApp;
/** An ordinary object. Main explicitly calls update and draw. */
public class Player {
private double x;
private double y;
public Player(double x, double y) {
this.x = x;
this.y = y;
}
public void update(double targetX, double targetY, double seconds) {
double amount = Math.min(1, seconds * 5);
x += (targetX - x) * amount;
y += (targetY - y) * amount;
}
public void draw(SketchApp app) {
app.fill(Color.web("#4878e8"));
// Circle positions describe the centre; rectangles use the top-left.
app.circle(x, y, 44);
}
}