|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
目标: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); }
- }
复制代码
|
|