我需要创建一个动画,其中屏幕上有一个球。我需要将球停到屏幕上。
我尝试使用此解决方案:
boolean collision =
bullet.getBoundsInParent().getMaxX()>=View.getInstance().getXLimit() ||
bullet.getBoundsInLocal().getMaxY()>=View.getInstance().getYLimit();
为了检测碰撞,但是它只能工作一段时间!我试图通过使用“ relocate()”方法来重定位球,但是当我对“ getBoundsInParent()。getMaxX()”进行分类时,它将返回屏幕限制的相同值,并且我无法重新启动动画。
我该如何解决问题?
答案 0 :(得分:0)
由于您未提供任何相关代码,因此我将使用here中的示例。
替换
deltaX *= -1; and deltaY *= -1;
with
deltaX = 0;
deltaY = 0;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Bounds;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class GamePractice extends Application
{
public static Circle circle;
public static Pane canvas;
@Override
public void start(final Stage primaryStage)
{
canvas = new Pane();
final Scene scene = new Scene(canvas, 800, 600);
primaryStage.setTitle("Game");
primaryStage.setScene(scene);
primaryStage.show();
circle = new Circle(15, Color.BLUE);
circle.relocate(100, 100);
canvas.getChildren().addAll(circle);
final Timeline loop = new Timeline(new KeyFrame(Duration.millis(10), new EventHandler<ActionEvent>()
{
double deltaX = 3;
double deltaY = 3;
@Override
public void handle(final ActionEvent t)
{
circle.setLayoutX(circle.getLayoutX() + deltaX);
circle.setLayoutY(circle.getLayoutY() + deltaY);
final Bounds bounds = canvas.getBoundsInLocal();
final boolean atRightBorder = circle.getLayoutX() >= (bounds.getMaxX() - circle.getRadius());
final boolean atLeftBorder = circle.getLayoutX() <= (bounds.getMinX() + circle.getRadius());
final boolean atBottomBorder = circle.getLayoutY() >= (bounds.getMaxY() - circle.getRadius());
final boolean atTopBorder = circle.getLayoutY() <= (bounds.getMinY() + circle.getRadius());
if (atRightBorder || atLeftBorder) {
deltaX = 0;
deltaY = 0;
}
if (atBottomBorder || atTopBorder) {
deltaY = 0;
deltaX = 0;
}
}
}));
loop.setCycleCount(Timeline.INDEFINITE);
loop.play();
}
public static void main(final String[] args)
{
launch(args);
}
}