java - 如何让我的弹跳球移动?

标签 java ios animation javafx timeline

所以我正在编写一个程序,让球在屏幕上弹跳,但当我启动它时,球根本不动。我使用时间轴的动画值,dy 和 dx 作为我在屏幕上的半径边界。

public class BallPane extends Pane {

public final double radius = 5;
public double x = radius, y = radius;
public double dx = 1, dy = 1;
public Circle circle = new Circle(x, y, radius);
public Timeline animation;

public BallPane(){
//sets ball position
x += dx; 
y += dy; 
circle.setCenterX(x); 
circle.setCenterY(y);

circle.setFill(Color.BLACK);
getChildren().add(circle); 

// Create animation for moving the Ball
animation = new Timeline(
    new KeyFrame(Duration.millis(50), e -> moveBall() ));
animation.setCycleCount(Timeline.INDEFINITE);
animation.play();
}    

public void play(){
    animation.play();
}

public void pause(){
    animation.pause();
}

public DoubleProperty rateProperty(){
    return animation.rateProperty();
}

public void moveBall(){
// Check Boundaries
    if(x < radius || x > getWidth() - radius) {
        dx *= -1; //change Ball direction
    }
    if(y < radius|| y > getHeight() - radius) {
        dy *= -1; //change Ball direction
    }
}
}

这是我的启动代码:

    public class BounceBallControl extends Application {

@Override
public void start(Stage stage) {

    BallPane ballPane = new BallPane(); // creates the ball pane

    ballPane.setOnMousePressed( e -> ballPane.pause());
    ballPane.setOnMouseReleased( e -> ballPane.play());

    Scene scene = new Scene(ballPane, 300, 250);
    stage.setTitle("BounceBall!");
    stage.setScene(scene);
    stage.show();

    ballPane.requestFocus();
}
public static void main(String[] args){
   launch(args);
}

我去掉了提高速度和降低速度的方法,因为它们似乎无关紧要(以防有人想知道速度设置为 animation.setRate(animation.getRate() + 0.1)。为什么我的球(根本)不动,它留在角落里?

最佳答案

你实际上不是relocating当你移动球时。

请参阅下面的示例,它将球重新置于新的 x 和 y 坐标位置的中心以移动它。

public void moveBall() {
    x += dx;
    y += dy;

    // Check Boundaries
    if (x < radius || x > getWidth() - radius) {
        dx *= -1; //change Ball direction
    }
    if (y < radius || y > getHeight() - radius) {
        dy *= -1; //change Ball direction
    }

    circle.setCenterX(x);
    circle.setCenterY(y);
}

请注意,您可以完全取消单独的 x 和 y 变量,因为它们的值已经通过圆的 centerX 和 centerY 属性表示,但我在上面的代码中保留了您的 x 和 y 变量,以便不要与您最初编码的解决方案有太大差异。

关于java - 如何让我的弹跳球移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36294786/

相关文章:

java - 将某些 Flink 操作优先于其他操作

java - 在 Nexus 上上传 jar 后 Maven 项目中出现 ClassNotFound 异常

ios - 从自定义 UITableViewCell 到带有数据的弹出 View 的 Segue 方式

javascript - Contenteditable 高度动画 : animate only after a line is deleted

jquery - 如何停止 jQuery 动画并稍后恢复?

java - 在jsp和java之间重用变量名(Spring)

java - 如果我想在用 Java 上传之前压缩视频,我有什么选择?

ios - AVPlayerItem 加载未知文件扩展名(缓存文件)

ios - 在 KeyboardDidShow 上切换 UIBarButtonItem

javascript - 为什么我的 setInterval 函数第二次不起作用? (JavaScript)