如何实现javafx 弹球游戏
目标:1.当球接触到窗口边界回弹 2.当球接触到黑色长方体回弹已实现:球接触到窗口回弹
未完成:当球接触到黑色长方体回弹
问题:如何让球与长方体接触后回弹,我尝试过了好多种方法但都不理想
以下是代码
package pong;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
public class Pong extends Application {
private double x, y, dx, dy;
@Override
public void start(Stage stage) {
Group root = new Group();
Scene scene = new Scene(root, 900, 700);
Circle orb = new Circle(10, Color.BLACK);
x = 450;
y = 350;
dx=5;
dy=5;
orb.relocate(450, 350);
Rectangle rect = new Rectangle(80,450,Color.BLACK);
rect.relocate(200,250);
root.getChildren().add(orb);
root.getChildren().add(rect);
stage.setTitle("Pong");
stage.setScene(scene);
stage.show();
new AnimationTimer() {
@Override
public void handle(long now) {
x += dx;
y += dy;
if ( x < 0 || x> scene.getWidth() ){
dx = -dx;
}
if ( y < 0|| y>scene.getHeight()){
dy= -dy;
}
orb.relocate(x, y);
}
}.start();
}
public static void main( String[] args ) { launch(args); }
}
package pong;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
public class Pong extends Application {
private double x, y, dx, dy;
private double rWidth, rHeight, rx, ry;
@Override
public void start(Stage stage) {
Group root = new Group();
Scene scene = new Scene(root, 900, 700);
Circle orb = new Circle(10, Color.BLACK);
x = 450;
y = 350;
dx=5;
dy=5;
orb.relocate(450, 350);
rWidth = 80;
rHeight = 450;
rx = 200;
ry = 250;
Rectangle rect = new Rectangle(rWidth,rHeight,Color.BLACK);
rect.relocate(rx,ry);
root.getChildren().add(orb);
root.getChildren().add(rect);
stage.setTitle("Pong");
stage.setScene(scene);
stage.show();
new AnimationTimer() {
@Override
public void handle(long now) {
x += dx;
y += dy;
if ( x < 0 || x> scene.getWidth() ){
dx = -dx;
}
if ( y < 0|| y>scene.getHeight()){
dy= -dy;
}
orb.relocate(x, y);
}
}.start();
new AnimationTimer() {
@Override
public void handle(long now) {
x += dx;
y += dy;
if (x == rWidth+rx && (y > ry && y < rHeight+rx)){
dx = -dx;
}
if (x == rx && (y > ry && y < rHeight+rx)) {
dx = -dx;
}
if (y == ry && (x >= rx && x <= rWidth+rx)) {
dy = -dy;
}
if (y == rHeight+rx && (x >= rx && x <= rWidth+rx)) {
dy = -dy;
}
orb.relocate(x, y);
}
}.start();
}
public static void main( String[] args ) { launch(args); }
} 感谢! 临时号 发表于 2022-6-21 16:22
但小球在底部会穿过长方体
页:
[1]