【发布时间】:2015-10-11 07:25:50
【问题描述】:
我创建了一个程序,可以在屏幕上创建一个可以使用 W A S D 键盘键移动的黑色小圆圈。现在我正在尝试使黑色圆圈不会超出舞台范围(目前确实如此)。我的想法是创建一个采用 2 个参数的方法:圆和舞台。该方法的工作原理如下:
if(circle.getBoundsInParent().intersects(stage)) {
MOVEMENT_SPEED = 0
}
这个方法应该是检查圆是否与舞台相交,如果相交,则将球的移动速度设置为零,从而阻止他通过舞台。然而,
circle.getBoundsInParent().intersects(stage))
代码不起作用。它说舞台不能转换为边界。为了检查人物和舞台碰撞并防止人物移出舞台债券,我需要做什么?
这是我当前的代码。
package pong;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class Main extends Application {
private static int MOVEMENT_SPEED = 10;
@Override
public void start(Stage primaryStage) {
final Circle circle = createCircle();
final Group group = new Group( circle);
Scene scene = new Scene(group, 700, 700);
move(scene, circle);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
private void move(Scene scene, final Circle circle) {
scene.setOnKeyPressed((KeyEvent event) -> {
switch (event.getCode()) {
case W: circle.setCenterY(circle.getCenterY() - MOVEMENT_SPEED);
break;
case D: circle.setCenterX(circle.getCenterX() + MOVEMENT_SPEED);
break;
case S: circle.setCenterY(circle.getCenterY() + MOVEMENT_SPEED);
break;
case A: circle.setCenterX(circle.getCenterX() - MOVEMENT_SPEED);
break;
}
});
}
private Circle createCircle() {
final Circle circle = new Circle(10, 10, 10, Color.BLACK);
circle.setOpacity(0.7);
return circle;
}
// This method should detect collision and prevent it from happening
private void detectCollsion(Circle circle, Stage primaryStage) {
/* if(circle.getBoundsInParent().intersects(primaryStage)) {
MOVEMENT_SPEED = 0;
} */
}
}
【问题讨论】:
-
我认为与其编写一个检测碰撞的方法并费尽心思检测圆将碰撞的一侧,不如通过在 switch 语句中添加条件来实现。