How to check for Shape intersection using GeneralPath? Java
-
10-03-2021 - |
Domanda
I have a program that allows you to move various Shapes about. I want to be able to return a boolean that returns true if two shapes are intersecting. This is what I have thus far:
public boolean overlaps(MyShape s){
Rectangle2D.Double otherShapeBoundary
= new Rectangle2D.Double(s.getX(), s.getY(), s.getWidth(), s.getHeight());
PathIterator pi = path.getPathIterator(null);
return path.intersects(pi,otherShapeBoundary);
}
...where path is a GeneralPath (these are all straight from the API, except MyShape).
One thing I'm unsure on is how PathIterator works, which might be the problem. I've also tried this, but I was getting a similar error:
public boolean overlaps(OverlappableSceneShape s){
Rectangle2D.Double otherShapeBoundary
= new Rectangle2D.Double(s.getX(), s.getY(), s.getWidth(), s.getHeight());
return path.intersects(otherShapeBoundary);
}
The error is that this method almost always returns false. I'm unsure when/why it is returning true, but it is very infrequent.
Soluzione
What I tried second was actually the correct answer. Just to be clear:
public boolean overlaps(OverlappableSceneShape s){
Rectangle2D.Double otherShapeBoundary
= new Rectangle2D.Double(s.getX(), s.getY(), s.getWidth(), s.getHeight());
return path.intersects(otherShapeBoundary);
}
- is the best method of determining intersection.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow