我必须创建两个球,这些球在使用javaFX碰撞时会改变方向。
在一本教程书中,有一个有关碰撞的解释,但似乎不起作用。
这里是管理碰撞的球类:
private void controleerBotsing() {
if (this.intersects(andereBal.getLayoutBounds())) {
double temp = dx;
dx = andereBal.dx;
andereBal.dx = temp;
temp = dy;
dy = andereBal.dy;
andereBal.dy = temp;
}
}
在我的代码中,我的球类是这样的:
package vbxxyy;
import javafx.geometry.Bounds;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.RadialGradient;
import javafx.scene.paint.Stop;
import javafx.scene.shape.Circle;
public class Biljartbal extends Circle {
private final int straal;
private final Color kleur;
private final double maxX, maxY;
private double dx, dy;
public Biljartbal(int x, int y, int straal, Color kleur, double maxX, double maxY) {
super(x, y, straal);
this.kleur = kleur;
this.straal = straal;
this.maxX = maxX;
this.maxY = maxY;
final RadialGradient gradient = new RadialGradient(0, 0, .35, .35, .5,
true, CycleMethod.NO_CYCLE, new Stop(0.0, Color.WHITE), new Stop(1.0, kleur));
this.setFill(gradient);
dx = 3 * Math.random() + 1;
dy = 4 * Math.random() + 1;
}
public void verplaats() {
setCenterX(getCenterX() + dx);
setCenterY(getCenterY() + dy);
// Als je voorbij de linker- of rechterkant bent, draai dan de x-richting om
if((getCenterX() < straal) || (getCenterX() >= maxX - straal))
dx = -dx;
// Als je voorbij de onder- of bovenkant bent, draai dan de y-richting om
if((getCenterY() >= maxY - straal) || (getCenterY() < straal))
dy = -dy;
}
}
还有带有时间表和关键帧的窗格,如下所示:
package vbxxyy;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.util.Duration;
public class Vb1205 {
public final Biljartbal bal, bal2;
public final KeyFrame keyframe1, keyframe2;
public final Timeline timeline1, timeline2;
public Vb1205(Pane p) {
bal = new Biljartbal(30, 40, 20, Color.RED, p.getWidth(), p.getHeight());
bal2 = new Biljartbal(30, 40, 20, Color.BLUE, p.getWidth(), p.getHeight());
p.getChildren().addAll(bal, bal2);
keyframe1 = new KeyFrame(Duration.millis(15), e -> bal.verplaats());
keyframe2 = new KeyFrame(Duration.millis(15), e -> bal2.verplaats());
timeline1 = new Timeline(keyframe1);
timeline2 = new Timeline(keyframe2);
timeline1.setCycleCount(Timeline.INDEFINITE);
timeline2.setCycleCount(Timeline.INDEFINITE);
timeline1.play();
timeline2.play();
}
}
是否有解决两个球之间碰撞的解决方案?
有人可以帮助我吗?