我正在尝试制作汽车从左向右移动的动画。如果它到达右端,它将重新开始。使用PathTransition
可以轻松完成此类动画。但是我必须在动画期间通过UP / DOWN键改变车速。出于某种原因,我无法使用PathTransition。
所以,我正在做一个简单的动画。但在这种情况下,汽车并没有动。有人可以帮助我找到我的错误:
package exercise_15_29;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
import javafx.animation.KeyFrame;
public class Exercise_15_29 extends Application {
static Group car = new Group();
Circle wheel1 = new Circle(15, 95, 5);
Circle wheel2 = new Circle(35, 95, 5);
Polygon body1 = new Polygon();
Rectangle body2 = new Rectangle(0.0, 80.0, 50, 10);
Line path = new Line(0, 90, 500, 90);
int speed = 100;
boolean play = true;
public static void main(String[] args) {
launch(args);
}
public static void moveCar(){
if(car.getLayoutX() == 500)
car.setTranslateX(-500);
else
car.setTranslateX(10);
}
@Override
public void start(Stage primaryStage) {
body1.getPoints().addAll(new Double[]{
10.0, 80.0,
20.0, 70.0,
30.0, 70.0,
40.0, 80.0
});
body1.setFill(Color.BLUE);
body2.setFill(Color.SKYBLUE);
path.setVisible(false);
car.getChildren().addAll(wheel1, wheel2, body1, body2);
Timeline animation = new Timeline(new KeyFrame(Duration.millis(speed),e -> moveCar()));
animation.setCycleCount(Timeline.INDEFINITE);
animation.play();
Pane root = new Pane();
root.getChildren().add(car);
root.getChildren().add(path);
Scene scene = new Scene(root, 500, 100);
scene.addEventFilter(KeyEvent.KEY_PRESSED, e -> {
if (e.getCode() == KeyCode.P) {
if (play)
animation.pause();
else
animation.play();
play = !play;
}
});
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
scene.setOnKeyPressed(e -> {
if (e.getCode() == KeyCode.UP)
animation.setRate(animation.getRate() + 0.1);
else if (e.getCode() == KeyCode.DOWN){
animation.setRate(
animation.getRate() > 0 ? animation.getRate() - 0.1 : 0);
}
});
}
}