Created
June 6, 2019 14:29
-
-
Save skrb/8e6cea387432bb933533a7461fa44010 to your computer and use it in GitHub Desktop.
AnimationTimerのサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.List; | |
import java.util.Random; | |
import java.util.stream.Collectors; | |
import javafx.animation.AnimationTimer; | |
import javafx.application.Application; | |
import javafx.scene.Node; | |
import javafx.scene.Scene; | |
import javafx.scene.layout.Pane; | |
import javafx.scene.paint.Color; | |
import javafx.scene.shape.Rectangle; | |
import javafx.stage.Stage; | |
public class AnimationDemo extends Application { | |
private long previous = 0; | |
private final Random random = new Random(); | |
private static final double WIDTH = 600; | |
private static final double HEIGHT = 400; | |
@Override | |
public void start(Stage stage) throws Exception { | |
Pane root = new Pane(); | |
Scene scene = new Scene(root, WIDTH, HEIGHT); | |
scene.setFill(Color.BLACK); | |
stage.setScene(scene); | |
stage.show(); | |
startAnimation(root); | |
} | |
private void startAnimation(Pane root) { | |
AnimationTimer timer = new AnimationTimer() { | |
@Override | |
public void handle(long t) { | |
if (previous == 0) { | |
previous = t; | |
} | |
// 適当なタイミングで四角を生成 | |
if (random.nextDouble() < 0.02) { | |
Rectangle rect = new Rectangle(WIDTH, random.nextDouble() * HEIGHT, 20, 20); | |
rect.setFill(Color.WHITE); | |
root.getChildren().add(rect); | |
} | |
// 四角を移動 | |
// 左側まで移動したら削除候補とする | |
List<Node> removedRects | |
= root.getChildren().stream() | |
.map(node -> (Rectangle) node) | |
.map(rect -> { | |
double x = rect.getX(); | |
x -= (t - previous) / 10_000_000.0; | |
rect.setX(x); | |
double y = rect.getY(); | |
y += random.nextDouble() * 2.0 - 1.0; | |
rect.setY(y); | |
return rect; | |
}) | |
.filter(rect -> { | |
double x = rect.getX(); | |
if (x < -WIDTH) { | |
return true; | |
} else { | |
return false; | |
} | |
}) | |
.collect(Collectors.toList()); | |
// 左まで移動した四角を削除 | |
root.getChildren().removeAll(removedRects); | |
previous = t; | |
} | |
}; | |
timer.start(); | |
} | |
public static void main(String... args) { | |
launch(args); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment