如何利用JavaFx编写一个球绕特定的轨迹移动(以三角函数为例)详细代码包含解析

import javafx.animation.PathTransition;
import javafx.animation.PathTransition.OrientationType;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.shape.Polyline;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;

public class ArcBall extends Application{

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		launch(args);

	}

	@Override
	public void start(Stage stage) throws Exception {
		// TODO Auto-generated method stub
		Pane pane=new Pane();
		//绘制坐标轴
		Line line1=new Line(10,100,390,100);
		//x轴上的箭头
		Line l1=new Line(390,100,370,90);
		Line l2=new Line(390,100,370,110);
		Text text1=new Text(380,70,"X");
		Line line2=new Line(200,10,200,200);
		//y轴上的箭头
		Line l3=new Line(200,10,190,30);
		Line l4=new Line(200,10,210,30);
		Text text2=new Text(220,20,"Y");
		//将PI放进坐标轴中
		Text text3=new Text(90,115,"-2\u03c0");// \u03c0为PI的Unicode码
		Text text4=new Text(140,115,"-\u03c0");
		Text text5=new Text(200,115,"0");
		Text text6=new Text(250,115,"\u03c0");
		Text text7=new Text(300,115,"2\u03c0");
		//绘制三角函数
		Polyline p=new Polyline();
		ObservableList<Double> list=p.getPoints();
		double facter=50;//三角函数的峰高
		for(int i=-170;i<=170;i++) {
			list.add(i+200.0);//x的坐标,加200是因为对称,x越来越大
			list.add(100-facter*Math.sin((i/100.0)*2*Math.PI));//y的坐标,从左到右y是一个先变大后变小的一个循环
		}
		Circle cir=new Circle(30,100-facter*Math.sin((-170/100.0)*2*Math.PI),10);
		
		PathTransition pt=new PathTransition();//轨迹动画
		pt.setDuration(Duration.millis(4000));//设置周期
		pt.setNode(cir);//圆为节点
		pt.setPath(p);//轨迹为三角函数
		pt.setOrientation(OrientationType.ORTHOGONAL_TO_TANGENT);//设置轨迹方向
		pt.setCycleCount(Timeline.INDEFINITE);//无限循环
		pt.setAutoReverse(true);
		pt.play();//启动动画
		pane.getChildren().addAll(line1,line2,l1,l2,l3,l4,text1,text2,text3,text4,text5,text6,text7,p,cir);
		//增加鼠标事件 进行控制
		pane.setOnMouseClicked(e ->{
			if(e.getButton()==MouseButton.PRIMARY) {
				pt.play();
			}
			if(e.getButton()==MouseButton.SECONDARY) {
				pt.pause();
			}
		});
		Scene scene =new Scene(pane,400,250);
		stage.setTitle("JavaFx");
		stage.setScene(scene);
		stage.show();
		
	
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值