2015-06-08 80 views
0

我正在使用JavaFx 8庫。javafx碰撞問題的路徑(行)與粗筆畫和圓圈

我的任務很簡單:我想檢查一下圓周是否與周圍有粗的筆畫碰撞。問題是Path.intersect()和Shape.intersect()函數都會忽略路徑/線條周圍的筆劃。

Path tempPath = new Path(player.getPath().getElements()); 
//player.getDot() is Circle 
if(tempPath.intersects(player.getDot().getBoundsInParent())){ 
    Shape intersect = Shape.intersect(tempPath, player.getDot()); 
    if(intersect.getBoundsInLocal().getWidth() != -1){ 
     System.out.println("Path Collision occurred"); 
    } 
} 

我的路徑是由許多LineTo對象組成的。 格式是這樣的:

/** Creates path and player dot */ 
private void createPath() { 
    this.path = new Path(); 
    this.path.setStrokeWidth(20); 
    this.path.setStroke(Color.RED); 
    this.path.setStrokeLineCap(StrokeLineCap.ROUND); 
    this.path.setStrokeLineJoin(StrokeLineJoin.ROUND); 

    this.dot = new Circle(10, Color.BLUE); 
    this.dot.setOpacity(1); 
} 

我該如何實現成功的碰撞檢測?

回答

1

碰撞檢測工作得很好:

import javafx.application.Application; 
import javafx.scene.Scene; 
import javafx.scene.layout.BorderPane; 
import javafx.scene.layout.Pane; 
import javafx.scene.shape.Circle; 
import javafx.scene.shape.ClosePath; 
import javafx.scene.shape.LineTo; 
import javafx.scene.shape.MoveTo; 
import javafx.scene.shape.Path; 
import javafx.scene.shape.Shape; 
import javafx.scene.shape.StrokeLineCap; 
import javafx.scene.shape.StrokeLineJoin; 
import javafx.stage.Stage; 

public class Main extends Application { 
    @Override 
    public void start(Stage primaryStage) { 

     BorderPane root = new BorderPane(); 

     Circle circle = new Circle(100, 100, 30); 
     Path path = new Path(); 

     double x = 144; 

     path.getElements().add(new MoveTo(x, 140)); 
     path.getElements().add(new LineTo(500, 100)); 
     path.getElements().add(new ClosePath()); 

     path.setStrokeWidth(60); 
     path.setStrokeLineCap(StrokeLineCap.ROUND); 
     path.setStrokeLineJoin(StrokeLineJoin.ROUND); 

     Shape shape = Shape.intersect(circle, path); 

     boolean intersects = shape.getBoundsInLocal().getWidth() != -1; 

     System.out.println("Intersects: " + intersects); 

     Pane pane = new Pane(); 
     pane.getChildren().addAll(circle, path); 
     root.setCenter(pane); 

     Scene scene = new Scene(root, 800, 600); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 

    } 

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

開關X = 144 X = 145進行測試。控制檯顯示是否有交叉點。

您遇到的問題是您正在比較不同的邊界。

有關如何計算各種邊界的信息,請參閱Node的文檔「邊界矩形」的文檔。

+0

你是對的,碰撞工作正常。我發現我的錯誤在Path對象的重複中。 Path tempPath = new Path(player.getPath()。getElements());) 舊路徑的屬性(如Stroke和Color)沒有轉移到新路徑。因此需要重新分配屬性。 –