我是初学者。我正在制作一个简单的2D游戏。在游戏中,彩色圆圈穿过彩色矩形障碍物。它必须匹配颜色。游戏循环是使用时间轴实现的。现在,我希望动画的速度在时间轴的每次迭代中都增加。也就是说,矩形每次迭代必须更快。我已经在检查此网站和其他方法的handle方法中完成了以下代码。但这是行不通的。
double duration = timeline.getCycleDuration().toMillis();
if(duration > 1) {
duration -= 100;
timeline.setRate(timeline.getCycleDuration().toMillis()/duration);
}
我该如何实现?我已经检查了该网站上的所有帖子,但无法实施。这是我的完整代码。
final double frameDuration = 16;
final double iterationDuration = 4000;
final int framesPerIteration = (int) (iterationDuration / frameDuration + 1);
randomizeColors(rectangles, circle, colors);
Timeline timeline = new Timeline();
class FrameHandler implements EventHandler<ActionEvent> {
private KeyCode code;
private int frame = 1;
public boolean lost = false;
private void lostAction() {
timeline.stop();
restartButton.setVisible(true);
quitButton.setVisible(true);
}
@Override
public void handle(ActionEvent event) {
if (frame == 0) {
randomizeColors(rectangles, circle, colors); // change colors when iteration is done
}
double duration = timeline.getCycleDuration().toMillis();
if(duration > 1) {
duration -= 100;
timeline.setRate(timeline.getCycleDuration().toMillis()/duration);
}
// move circle, if key is pressed
if (code != null) {
switch (code) {
case RIGHT:
circle.setCenterX(circle.getCenterX()
+ KEYBOARD_MOVEMENT_DELTA);
break;
case LEFT:
circle.setCenterX(circle.getCenterX()
- KEYBOARD_MOVEMENT_DELTA);
break;
}
}
// move rects & check intersection
final Paint color = circle.getFill();
final double cx = circle.getCenterX();
final double cy = circle.getCenterY();
final double r2 = circle.getRadius() * circle.getRadius();
for (Rectangle rect : rectangles) {
rect.setY(frame * RECT_MAX_Y / framesPerIteration);
// check for intersections with rects of wrong color
if (rect.getFill() != color) {
double dy = Math.min(Math.abs(rect.getY() - cy),
Math.abs(rect.getY() + rect.getHeight() - cy));
dy = dy * dy;
if (dy > r2) {
{
//increaseSpeed();
continue;} // y-distance too great for intersection
}
if (cx >= rect.getX() && cx <= rect.getX() + rect.getWidth()) {
lost = true;
} else {
double dx = Math.min(Math.abs(rect.getX() - cx),
Math.abs(rect.getX() + rect.getWidth() - cx));
if (dx * dx + dy <= r2) {
lost = true;
}
}
}
}
frame = (frame + 1) % framesPerIteration;
if (lost) {
lostAction();
}
}
}
FrameHandler frameHandler = new FrameHandler();
Scene scene = new Scene(root);// keep track of the state of the arrow keys
scene.setOnKeyPressed(evt -> {
KeyCode code = evt.getCode();
switch (code) {
case RIGHT:
case LEFT:
frameHandler.code = code;
break;
}
});
scene.setOnKeyReleased(evt -> {
KeyCode code = evt.getCode();
if (frameHandler.code == code) {
frameHandler.code = null;
}
});
timeline.getKeyFrames().add(new KeyFrame(Duration.millis(frameDuration), frameHandler));
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();