圆和矩形之间的碰撞在角落中不起作用(javafx)

时间:2017-04-28 14:51:55

标签: java javafx collision-detection collision shape

Greetings SOCommunity,

现在我正在尝试学习形状之间的碰撞检测。检测本身工作正常。但是对象的重新定位并不完整。

因此,只要我的圆圈触及矩形的角落,重新定位就无法工作。

这是我的代码:

public class Collision extends Application {

@Override
public void start(Stage stage) {

    Group root = new Group();
    Scene scene = new Scene(root, 600, 600, Color.CADETBLUE);

// Nodes
    Rectangle bounds = new Rectangle(500,500, Color.TRANSPARENT);
    bounds.setStroke(Color.WHITE);
    bounds.setStrokeWidth(5);
    bounds.setTranslateX(50);
    bounds.setTranslateY(50);

    Circle c1 = new Circle(30, Color.WHITE);
    c1.setTranslateX(300);
    c1.setTranslateY(300);

// Events

    // Collision Detection and c1 movement
    EventHandler<MouseEvent> handle = new EventHandler<MouseEvent>() {      

        double difX;    // Circle to mouse difference
        double difY;

        double reloX;   // Circle touches bounds
        double reloY;

        Bounds nodeBounds = c1.getBoundsInLocal();  // Bound Objects for Node and Rect
        Bounds bound = bounds.getBoundsInLocal();

        public void handle(MouseEvent event) {

            // If Pressed save Coordinates
            if(event.getEventType() == MouseEvent.MOUSE_PRESSED) {

                difX = event.getX();
                difY = event.getY();      

            }
            // If Dragged check Collision and relocate
            else if(event.getEventType() == MouseEvent.MOUSE_DRAGGED) {

                c1.setTranslateX( event.getSceneX() - difX );
                c1.setTranslateY( event.getSceneY() - difY );


                if( c1.localToScene(nodeBounds).getMinX() < bounds.localToScene(bound).getMinX() ) {
                    bounds.setStroke(Color.RED);
                    c1.setTranslateX( bound.getMinX() - nodeBounds.getMinX() + 50 );
                }
                else if( c1.localToScene(nodeBounds).getMinY() < bounds.localToScene(bound).getMinY() ) { 
                    bounds.setStroke(Color.RED);
                    c1.setTranslateY( bound.getMinY() - nodeBounds.getMinY() + 50 );
                }
                else if( c1.localToScene(nodeBounds).getMaxX() > bounds.localToScene(bound).getMaxX() ) { 
                    bounds.setStroke(Color.RED);
                    c1.setTranslateX( bound.getMaxX() - nodeBounds.getMaxX() + 50 );
                }
                else if( c1.localToScene(nodeBounds).getMaxY() > bounds.localToScene(bound).getMaxY() ) { 
                    bounds.setStroke(Color.RED);
                    c1.setTranslateY( bound.getMaxY() - nodeBounds.getMaxY() + 50 );
                }                   
                else {
                    bounds.setStroke(Color.WHITE);
                }

            }       


        }
    };

    c1.addEventHandler(MouseEvent.ANY, handle);

//Stage is setUp
    root.getChildren().addAll(bounds, c1);
    stage.setTitle("omfg, srsly !?");
    stage.setScene(scene);
    stage.show();
}

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

请帮助我找出为什么这不起作用以及如何让它工作。

提前Thx:)

1 个答案:

答案 0 :(得分:1)

这是一个你可以玩的应用程序来弄清楚你做错了什么。

  

主:

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

/**
 *
 * @author blj0011
 */
public class CollisionDection extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}
  

控制器:

import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Point2D;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;

/**
 *
 * @author sedj601
 */
public class FXMLDocumentController implements Initializable {

    @FXML private Label lblMain;
    @FXML private Polygon polyOne, polyTwo;    
    @FXML private Circle circle1;
    @FXML private Rectangle rectangle1;

    final ObjectProperty<Point2D> mousePosition = new SimpleObjectProperty<>();

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        polyOne.setOnMousePressed((MouseEvent event) -> {
            mousePosition.set(new Point2D(event.getSceneX(), event.getSceneY()));
        });

        polyOne.setOnMouseDragged((MouseEvent event) -> {
            double deltaX = event.getSceneX() - mousePosition.get().getX();
            double deltaY = event.getSceneY() - mousePosition.get().getY();
            polyOne.setLayoutX(polyOne.getLayoutX()+deltaX);
            polyOne.setLayoutY(polyOne.getLayoutY()+deltaY);
            mousePosition.set(new Point2D(event.getSceneX(), event.getSceneY()));

            Shape intersect = Shape.intersect(polyOne, polyTwo);

            if(intersect.getBoundsInLocal().getWidth() != -1)
            {
                System.out.println("This object can overlap other the other object!");
                lblMain.setText("Collision detected!");
            }
            else
            {
                intersect.getBoundsInLocal().getWidth();
                lblMain.setText("Collision not detected!");
            }            
        });

        polyTwo.setOnMousePressed((MouseEvent event) -> {
            mousePosition.set(new Point2D(event.getSceneX(), event.getSceneY()));
        });

        polyTwo.setOnMouseDragged((MouseEvent event) -> {
            double deltaX = event.getSceneX() - mousePosition.get().getX();
            double deltaY = event.getSceneY() - mousePosition.get().getY();
            polyTwo.setLayoutX(polyTwo.getLayoutX() + deltaX);
            polyTwo.setLayoutY(polyTwo.getLayoutY() + deltaY);
            mousePosition.set(new Point2D(event.getSceneX(), event.getSceneY()));

            Shape intersect = Shape.intersect(polyOne, polyTwo);
            {
                if(intersect.getBoundsInLocal().getWidth() != -1)
                {      
                    System.out.println("This object can not overlap other the other object!");
                    polyTwo.setLayoutX(polyTwo.getLayoutX() - deltaX);
                    polyTwo.setLayoutY(polyTwo.getLayoutY() - deltaY);
                    lblMain.setText("Collision detected!");
                }
                else
                {
                    lblMain.setText("Collision not detected!");
                }
            }
        });   

        circle1.setOnMousePressed((MouseEvent event) -> {
            mousePosition.set(new Point2D(event.getSceneX(), event.getSceneY()));
        });

        circle1.setOnMouseDragged((MouseEvent event) -> {
            double deltaX = event.getSceneX() - mousePosition.get().getX();
            double deltaY = event.getSceneY() - mousePosition.get().getY();
            circle1.setLayoutX(circle1.getLayoutX() + deltaX);
            circle1.setLayoutY(circle1.getLayoutY() + deltaY);
            mousePosition.set(new Point2D(event.getSceneX(), event.getSceneY()));

            Shape intersect = Shape.intersect(rectangle1, circle1);
            {
                if(intersect.getBoundsInLocal().getWidth() != -1)
                {      
                    System.out.println("This object can not overlap other the other object!");
                    circle1.setLayoutX(circle1.getLayoutX() - deltaX);
                    circle1.setLayoutY(circle1.getLayoutY() - deltaY);
                    lblMain.setText("Collision detected!");
                }
                else
                {
                    lblMain.setText("Collision not detected!");
                }
            }
        });   


        rectangle1.setOnMousePressed((MouseEvent event) -> {
            mousePosition.set(new Point2D(event.getSceneX(), event.getSceneY()));
        });

        rectangle1.setOnMouseDragged((MouseEvent event) -> {
            double deltaX = event.getSceneX() - mousePosition.get().getX();
            double deltaY = event.getSceneY() - mousePosition.get().getY();
            rectangle1.setLayoutX(rectangle1.getLayoutX() + deltaX);
            rectangle1.setLayoutY(rectangle1.getLayoutY() + deltaY);
            mousePosition.set(new Point2D(event.getSceneX(), event.getSceneY()));

            Shape intersect = Shape.intersect(circle1, rectangle1);
            {
                if(intersect.getBoundsInLocal().getWidth() != -1)
                {      
                    System.out.println("This object can not overlap other the other object!");
                    rectangle1.setLayoutX(rectangle1.getLayoutX() - deltaX);
                    rectangle1.setLayoutY(rectangle1.getLayoutY() - deltaY);
                    lblMain.setText("Collision detected!");
                }
                else
                {
                    lblMain.setText("Collision not detected!");
                }
            }
        });   
    }
}
  

FXML:

<AnchorPane id="AnchorPane" fx:id="apMain" prefHeight="446.0" prefWidth="577.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="collisiondection.FXMLDocumentController">
    <children>
        <Label fx:id="lblMain" layoutX="254.0" layoutY="408.0" minHeight="16" minWidth="69" />
      <Polygon fx:id="polyOne" fill="DODGERBLUE" layoutX="122.0" layoutY="166.0" stroke="BLACK" strokeType="INSIDE">
        <points>
          <Double fx:value="-50.0" />
          <Double fx:value="40.0" />
          <Double fx:value="50.0" />
          <Double fx:value="40.0" />
          <Double fx:value="0.0" />
          <Double fx:value="-60.0" />
        </points>
      </Polygon>
      <Polygon fx:id="polyTwo" fill="DODGERBLUE" layoutX="419.0" layoutY="166.0" stroke="BLACK" strokeType="INSIDE">
        <points>
          <Double fx:value="-50.0" />
          <Double fx:value="40.0" />
          <Double fx:value="50.0" />
          <Double fx:value="40.0" />
          <Double fx:value="0.0" />
          <Double fx:value="-60.0" />
        </points>
      </Polygon>
      <Circle fx:id="circle1" fill="DODGERBLUE" layoutX="113.0" layoutY="372.0" radius="42.0" stroke="BLACK" strokeType="INSIDE" />
      <Rectangle fx:id="rectangle1" arcHeight="5.0" arcWidth="5.0" fill="DODGERBLUE" height="100.0" layoutX="379.0" layoutY="314.0" stroke="BLACK" strokeType="INSIDE" width="113.0" />
    </children>
</AnchorPane>