1
我正在嘗試製作使用GraphicsContext2D繪製的三角形形狀,並沿着鼠標朝向它。JavaFX - 在移動小距離後跟隨鼠標斷斷續續的繪製形狀
當您移動超過10個像素的距離時,它可以很好地工作。但是,當您移動小精確距離並且不能正確對着鼠標時,形狀會出現斷斷續續的情況。
遊戲:
public class Game extends Application {
final static private String GAME_NAME = "Trigon";
final static private int WINDOW_WIDTH = 960;
final static private int WINDOW_HEIGHT = 640;
private PlayerShip ply;
@Override
public void start(Stage theStage) throws Exception {
// Set title of window & make root, canvas, graphics context
theStage.setTitle(GAME_NAME);
Group root = new Group();
Scene theScene = new Scene(root, WINDOW_WIDTH, WINDOW_HEIGHT);
Canvas canvas = new Canvas(WINDOW_WIDTH, WINDOW_HEIGHT);
GraphicsContext gc = canvas.getGraphicsContext2D();
theStage.setScene(theScene);
root.getChildren().add(canvas);
// Initialize game variables
ply = new PlayerShip(WINDOW_WIDTH/2, WINDOW_HEIGHT/2);
theScene.setOnMouseMoved(
new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
ply.setPos(e.getX(), e.getY());
}
}
);
new AnimationTimer() {
@Override
public void handle(long currentNanoTime) {
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
ply.draw(gc);
}
}.start();
theStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
PlayerShip:
public class PlayerShip {
private double shipLength, shipWidth;
private double posX, posY, rotAngle;
public PlayerShip(double posX, double posY) {
this(posX, posY);
}
public PlayerShip(double posX, double posY) {
this.posX = posX;
this.posY = posY;
this.shipWidth = 30;
this.shipLength = 30;
}
public void setPos(double posX, double posY) {
double distX = posX - this.posX;
double distY = posY - this.posY;
rotAngle = Math.toDegrees(Math.atan2(distX, -distY));
this.posX = posX;
this.posY = posY;
}
public void draw(final GraphicsContext gc) {
// Save
gc.save();
// Translate + rotate
gc.translate(posX, posY);
gc.rotate(rotAngle);
// Draw ship
gc.beginPath();
gc.moveTo(0, -shipLength/2);
gc.lineTo(shipWidth/2, shipLength/2);
gc.lineTo(-shipWidth/2, shipLength/2);
gc.lineTo(0, -shipLength/2);
gc.stroke();
gc.closePath();
// Restore
gc.restore();
}
}
對不起,文本塊,或者如果我忘記一些重要的事情。
哦!我明白!謝謝! – Festi