I want to make an image move from right to left and make the image appear on the right side of my pane randomly.The problem is that the image appears in the same place over and over again.
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.geometry.Rectangle2D;
import javafx.scene.image.ImageView;
import javafx.stage.Screen;
import javafx.util.Duration;
import java.util.Random;
public class Comet {
private static final int paneWidth = 1100;
private static final int paneHeight = 780;
private static final int cometWidth = 100;
private static final int cometHeight = 100;
private static final int duration = 3000;
private static final int delay = 1000;
private static final Random random = new Random();
public static void animateComet(ImageView imageView) {
imageView.setFitWidth(cometWidth);
imageView.setFitHeight(cometHeight);
double y = random.nextDouble() * (paneHeight - cometHeight);
imageView.setLayoutX(1100);
imageView.setLayoutY(y);
Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
double rightBound = screenBounds.getWidth() - cometWidth;
Timeline timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.setAutoReverse(false);
KeyFrame startKeyFrame = new KeyFrame(Duration.ZERO, new KeyValue(imageView.translateXProperty(), screenBounds.getWidth()));
KeyFrame endKeyFrame = new KeyFrame(Duration.millis(duration), new KeyValue(imageView.translateXProperty(), -paneWidth));
timeline.getKeyFrames().addAll(startKeyFrame, endKeyFrame);
timeline.setOnFinished(event -> {
double newPosition = random.nextDouble() * rightBound;
imageView.setTranslateX(newPosition);
timeline.playFromStart();
});
timeline.setDelay(Duration.millis(delay));
timeline.play();
}
}
I am basically stuck here.Whatever I try,it is the same problem.I tried changing the duration,changed the random function boundaries.I am not that good with coding.So I would appreciate if someone would help me.
Aucun commentaire:
Enregistrer un commentaire