I\'m creating a 2D game in Java using the Java2D library for drawing, and I really need a float-precision Polygon object that I can use both to draw game objects and to do c
Can you use a 3rd party library? If so, might I suggest to use the Slick 2D Polygon class. What I would do is internally, use this class for your actual Polygon to check intersection with contains and then when you need to draw, just cast the float
values to int
and draw the Java2D Polygon.
I know this might not be the optimal solution, but it might work for what you're doing.
Perhaps have the internals of the polygon at a different scale?
Multiply by a large number and typecast to int when writing to it, divide by the same large number when reading?
I would also recommend Path2D. GeneralPath is a legacy class; don't use it.
Path2D does provide access to the vertex values, albeit it a roundabout fashion. You need to use a PathIterator:
PathIterator pi = path.getPathIterator(null);
float[] value = new float[6];
float x = 0, y = 0;
while (!pi.isDone()) {
int type = pi.currentSegment(values);
if (type == PathIterator.SEG_LINETO) {
x = values[0];
y = values[1];
}
else if (type == PathIterator.SEG_CLOSE) {
x = 0;
y = 0;
}
else {
// SEG_MOVETO, SEG_QUADTO, SEG_CUBICTO
}
pi.next();
}
When you're ready to get fancy, you can expand that else to support the quadratic and cubic curves. I assume you don't need those at this time as you're talking about polygons.
Also, Path2D has some handy static methods for testing whether the path intersects a rectangle and whether the path contains a rectangle or point. Sadly, there are no methods for testing for a path intersecting or containing another path.