javafx小球運動

2020-09-27 09:00:55

javafx使用圖形介面在隨機位置生成顏色隨機、半徑隨機、初始運動速度隨機的小球,然後按照某種軌跡進行運動(運動軌跡方程自選),到邊界碰撞返回。

我太愛我的java張春鳳老師了,第一次寫部落格記錄程式設計生涯,新人還請多多關照!

根據大佬內容改編: link.

package application;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.paint.Color;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
import java.util.Timer;
import java.util.TimerTask;

public class MyWork extends Application {
	static int x = 200;
	static int y = 90;
	static double distance_x = Math.random() * 4 + 1;
	static double distance_y = Math.sqrt(25 - distance_x * distance_x);
	static Ellipse e = new Ellipse();
	static String temp1 = "left";
	static String temp2 = "down";

	// 只有第一次點選有效
	static Timer t = new Timer();
	static boolean record_start = true;
	static boolean record_stop = false;

	public static void main(String[] args) {
		launch(args);
	}

	public void start(Stage s) {

		Group root = new Group();
		Scene scene = new Scene(root, 400, 250, Color.WHITE);
		Button start = new Button("開始");
		Button stop = new Button("停止");

		// 分割線
		Line l = new Line();
		l.setStartX(0);
		l.setStartY(160);
		l.setEndY(160);
		l.setEndX(400);

		// 放置小球
		e.setCenterX((Math.random() * 400) + 1);
		e.setCenterY((Math.random() * 60) + 1);
		e.setRadiusX((Math.random() * 2) + 10);
		e.setRadiusY((Math.random() * 2) + 10);
		e.setFill(Color.rgb((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255)));
		start.setLayoutX(100);
		start.setLayoutY(190);
		stop.setLayoutX(250);
		stop.setLayoutY(190);
		start.setOnAction(event -> {

			if (record_start) {
				t = new Timer();
				t.schedule(new TimerTask() {
					public void run() {

						if (x < 20) {
							temp1 = "right";
						}
						if (x > 380) {
							temp1 = "left";
						}

						if (y < 20) {
							temp2 = "up";
						}
						if (y > 140) {
							temp2 = "down";
						}
						if (temp1.equals("left")) {
							e.setCenterX(x -= distance_x);
						} else {
							e.setCenterX(x += distance_x);
						}
						if (temp2.equals("down")) {
							e.setCenterY(y -= distance_y);
						} else {
							e.setCenterY(y += distance_y);
						}
					}
				}, 0, 20);
			}
			// 「開始"按鈕被點選且事件被觸發,record=false;
			record_start = false;
			record_stop = false;
		});

		stop.setOnAction(event -> {
			System.out.println("停止反彈");
			// 當第二次點選"停止"時,小球重置
			if (record_stop) {

				distance_x = Math.random() * 4 + 1;
				distance_y = Math.sqrt(25 - distance_x * distance_x);

				e.setCenterX((Math.random() * 400) + 1);
				e.setCenterY((Math.random() * 60) + 1);
				record_stop = false;
			}
			record_stop = true;
			record_start = true;
			t.cancel();
		});

		root.getChildren().addAll(start, stop, l, e);
		s.setTitle("小球反彈");
		s.setScene(scene);
		s.show();
	}
}

寫的不是很好,再接再厲好好學習!嘻嘻