Java 处理问题:使用矢量在画布上渲染图形
这里有一个特别的问题。我最近开始阅读Daniel Shiffman的书《代码的本质》,并开始练习Java和处理。在向量一章(第1章)的最后一个练习中,我不知道如何使我正在绘制的圆移动到光标。。。 这是移动类Java 处理问题:使用矢量在画布上渲染图形,java,animation,javafx,vector,processing,Java,Animation,Javafx,Vector,Processing,这里有一个特别的问题。我最近开始阅读Daniel Shiffman的书《代码的本质》,并开始练习Java和处理。在向量一章(第1章)的最后一个练习中,我不知道如何使我正在绘制的圆移动到光标。。。 这是移动类 public class Mover { PVector location; PVector acceleration; PVector velocity; double radius; float topSpeed; public Mover() { location = new
public class Mover {
PVector location;
PVector acceleration;
PVector velocity;
double radius;
float topSpeed;
public Mover() {
location = new PVector(200, 200);
velocity = new PVector(0,0);
topSpeed = 4;
}
public void update(){
float mx = (float) MouseInfo.getPointerInfo().getLocation().getX();
float my = (float) MouseInfo.getPointerInfo().getLocation().getY();
PVector mouse = new PVector(mx,my);
PVector dir = PVector.sub(mouse, location);
dir.normalize();
acceleration = dir;
velocity.add(acceleration);
velocity.limit(topSpeed);
location.add(velocity);
}
public void display(GraphicsContext g ){
g.clearRect(0,0,1000,800);
g.setFill(Color.RED);
g.fillOval(location.x,location.y, radius, radius);
}
使用FXMLLoader的主类:
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("Noc.fxml"));
primaryStage.setTitle("Hello World");
Scene tryout = new Scene(root, 1000, 800, true);
primaryStage.setScene(tryout);
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
这是主要的FXML类:
public class Noc {
@FXML
private Canvas can ;
GraphicsContext g;
Mover m = new Mover();
@FXML
private void initialize(){
g = can.getGraphicsContext2D();
can = new Canvas(1000, 800);
move();
}
private void move(){
AnimationTimer at = new AnimationTimer() {
@Override
public void handle(long l) {
m.radius = 30;
m.update();
m.checkBounds(); //function to check the edges of the canvas
m.display(g);
}
};
at.start();
}
}
我试过的所有其他例子都很好,但这一个似乎有问题。圆圈始终在距离鼠标150-200像素处停止。如果您能提供任何帮助/建议,我将不胜感激。@kleopatra我不确定我能不能将其简化得更多,或者您的意思是对代码块进行注释?请阅读参考的帮助页面并采取相应的行动(或者将您可以编译和运行这些代码段的神奇IDE发送给我:)
MouseInfo.getPointerInfo()
返回光标的屏幕位置,而不是其在后台的位置?如果是这样,那可能就是问题所在。