Reputation: 1
I am doing a JavaFX application and I have a board with multiple shape (circles and rectangle) added to a Pane. I don't want circle to be moved accross rectangle.
Circle are allowed to be dragged using Mouse Event (OnMousePressed,Dragged,Released) while rectangle are not allowed to move.
I am using this code to detect when my circle are colliding with the rectangles.
private void checkIntersection(Shape block) {
boolean collisionDetected = false;
for (Shape static_bloc : nodes) {
if (static_bloc != block) {
Shape intersect = Shape.intersect(block, static_bloc);
if (intersect.getBoundsInLocal().getWidth() != -1) {
collisionDetected = true;
}
}
}
if (collisionDetected) {
System.out.println("Collision detected");
} else {
System.out.println("Collision non deteted");
}
}
What I need to do is make my rectangle impossible to drag over while dragging circles. I don't want to send the shape back to his initial location. Is there a way to do this using intersect or am I missing something?
Upvotes: 0
Views: 1275
Reputation: 1285
Just wanted to share my solution.
I wanted to check the node before the movement was done. So I modified the previous solution, to create the following.
Node Class: I am working with a custom Node
class that extends Label
. The methods used here are those inherited from Label
.
private boolean hasNoCollision(Node dragged, double x, double y) {
// For each node
for (Node n : nodes) {
// If it is not the same, and future position overlaps
if (!n.equals(dragged) &&
n.getBoundsInParent().intersects(x, y, dragged.getWidth(), dragged.getHeight())) {
// Then prevent collission
return false;
}
}
// Otherwise all is good!
return true;
}
Upvotes: 0
Reputation: 1219
It's not so easy to answer. You can have a class for instance GameObject. This class contains your Shape. In this GameObject class you have your drag&drop logic. Then u will have a class GameObjectManager which contains list of all GameObjects. And every instance of GameObject will have a reference to this GameObjectManager so knows about all GameObjects as well. So in your move logic you can check if there is some collision between specific GameObject types and if, u can stop moving.
For collision assessment class GameObject contains method like:
protected boolean isInCollision() {
for (GameObject gameObject : gameObjectManager.getAllGameObjects()) {
if (!gameObject.equals(this)) {
if (getView().getBoundsInParent().intersects(gameObject.getView().getBoundsInParent())) {
return true;
}
}
}
return false;
}
In your case you need to loop just some types of objects in this isInCollision method.
Upvotes: 1