I'm trying to implement a cue stick into my pool game but I can't figure out how to get an image of a cuestick to rotate around the cueball.
I'm currently set it up so you can click and drag from the cue ball to draw a line.
private void startDrag(CueBall node, Pane root) {
currentLine = new Line();
currentLine.setUserData(node);
currentLine.setStartX(node.getxPosition());
currentLine.setStartY(node.getyPosition());
currentLine.endXProperty().bind(mouseX);
currentLine.endYProperty().bind(mouseY);
/**
* colors in a cue stick
*/
currentLine.setStrokeWidth(10);
String path = "cuestick.png";
Image img = new Image(path);
currentLine.setStroke(new ImagePattern(img));
currentLine.setStrokeLineCap(StrokeLineCap.ROUND);
root.getChildren().add(currentLine);
}
But this doesn't make the image rotate with the mouse.
Here is an example. Using Math.atan2
. This uses a Line
instead of an ImageView
, but the idea is the same. This approach is slightly different from the duplicate. It uses Math.atan2
to find the angle between the center and a point on the scene.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
/**
*
* @author blj0011
*/
public class QueAndStick extends Application
{
@Override
public void start(Stage primaryStage)
{
Circle cue = new Circle(300 / 2.0, 250 / 2.0, 5);
cue.setFill(Color.WHITE);
cue.setStroke(Color.BLACK);
Line stick = new Line(cue.getCenterX() + (cue.getRadius() + 5), cue.getCenterY(), cue.getCenterX() + (cue.getRadius() + 5 + 75), cue.getCenterY());
stick.setStrokeWidth(3);
stick.setFill(Color.BROWN);
Rotate rotate = new Rotate(45);
rotate.pivotXProperty().bind(cue.centerXProperty());
rotate.pivotYProperty().bind(cue.centerYProperty());
stick.getTransforms().add(rotate);
Pane root = new Pane(cue, stick);
root.setStyle("-fx-background-color: green");
Scene scene = new Scene(root, 300, 250);
scene.setOnMouseMoved((event) -> {
double newX = event.getSceneX();
double newY = event.getSceneY();
System.out.println(Math.toDegrees(Math.atan2(newY - cue.getCenterY(), newX - cue.getCenterX())));
rotate.setAngle(Math.toDegrees(Math.atan2(newY - cue.getCenterY(), newX - cue.getCenterX())));
});
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.