Перемщение фигуры - Java
Формулировка задачи:
Пишу игру пинг понг и столкнулся с проблемой джижения ракетки. Как её решить?Вот мой вариант:
Листинг программы
- import javafx.application.Application;
- import javafx.scene.shape.*;
- import javafx.scene.Parent;
- import javafx.stage.Stage;
- import javafx.scene.Scene;
- import javafx.scene.layout.Pane;
- import javafx.animation.KeyFrame;
- import javafx.animation.Timeline;
- import javafx.util.Duration;
- import javafx.scene.input.KeyCode;
- public class PingPong extends Application {
- Ball ball = new Ball(100, 300);
- Player rect = new Player();
- @Override
- public void start(Stage primaryStage) {
- Pane pane = new Pane();
- pane.getChildren().addAll(rect, ball);
- //----------------------------------------------------------------------
- rect.setOnKeyPressed(e -> {
- if (e.getCode() == KeyCode.ENTER)
- pane.getChildren().clear();
- rect.moveUp();
- pane.getChildren().addAll(rect, ball);
- });
- //-----------------------------------------------------------------------
- Scene scene = new Scene(pane, 400, 400);
- primaryStage.setScene(scene);
- primaryStage.show();
- }
- public class Player extends Rectangle {
- private int step = 1;
- public Player() {
- super(10, 50, 30, 200);
- }
- public void moveUp() {
- rect.setY(rect.getY() + step);
- }
- }
- public class Ball extends Circle {
- final static int RADIUS = 15;
- private int dx = 1, dy = 1;
- private Timeline animation;
- public Ball(int x, int y) {
- super(x, y,RADIUS);
- animation = new Timeline(new KeyFrame(Duration.millis(5), e -> moveBall()));
- animation.setCycleCount(Timeline.INDEFINITE);
- animation.play();
- }
- protected void moveBall() {
- if(ball.getCenterX() < ball.getRadius() || ball.getCenterX() > 400 - ball.getRadius())
- dx *=-1;
- if(ball.getCenterY() < ball.getRadius() || ball.getCenterY() > 400 - ball.getRadius())
- dy *=-1;
- if(collideX() && collideY()) {
- dx *=-1;
- // dy *=-1;
- }
- ball.setCenterX(ball.getCenterX() + ball.dx);
- ball.setCenterY(ball.getCenterY() + ball.dy);
- }
- public boolean collideX() {
- if(ball.getCenterX() - RADIUS < rect.getX() + rect.getWidth() && ball.getCenterX() > rect.getX())
- return true;
- return false;
- }
- public boolean collideY() {
- if(ball.getCenterY() - RADIUS < rect.getY() + rect.getHeight() && ball.getCenterY() > rect.getY())
- return true;
- return false;
- }
- }
- }
Решение задачи: «Перемщение фигуры»
textual
Листинг программы
- scene.setOnKeyPressed(e -> {
- if (e.getCode() == KeyCode.ENTER)
- pane.getChildren().clear();
- rect.moveUp();
- pane.getChildren().addAll(rect, ball);
- });
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д