 # Drawing java.awt.Shape

I’m using the java.awt.Shape class for collision detection with intersects() and contains(). However, this means that I’m duplication code, and in particular, magic numbers, when drawing vs checking collisions.

an Example:
a bit of the collider code

``````  public boolean contains(float x, float y, float facing, float checkX, float checkY) {
AffineTransform at = new AffineTransform();
at.translate(x,y);
at.rotate(facing);
Shape collider = at.createTransformedShape(collision);
return collider.contains(checkX,checkY);
}
``````

the code to create the collider:

``````  protected Shape createCollision() {
int[] xPoints = new int;
int[] yPoints = new int;
for(int vertex=0; vertex<3; vertex++) {
float angle=vertex*TWO_PI/3;
xPoints[vertex]=int(20*cos(angle));
yPoints[vertex]=int(20*sin(angle));
}
Polygon collision = new Polygon(xPoints,yPoints,3);
return collision;
}
``````

and the render code

``````  public void render(float x, float y, float facing) {
pushMatrix();
translate(x,y);
rotate(facing);
fill(110,82,255);
beginShape();
for(int vertex=0; vertex<3; vertex++) {
float angle=vertex*TWO_PI/3;
vertex(20*cos(angle),20*sin(angle));
}
endShape(CLOSE);
popMatrix();
}
``````

so as you can see, there’s quit a bit of code duplication there.
To fix this, I’d like to either:

• Draw the awt Shape directly (this is preferable)
or
• Create the Vertices/PShape based on the collider (or the inverse, create the collider from the render shape during construction)

Unfortunately, I know how to do neither of those using processing functions.

1 Like

I have some code to draw Shape in Processing inside PraxisLIVE.

Some of the code in this class might be helpful https://github.com/praxis-live/praxis/blob/master/praxis.video.pgl/src/org/praxislive/video/pgl/ops/PGLShapeRenderOp.java

PGLGraphics is basically PGraphics.

EDIT : incidentally, I’m using this with OpenGL. If you’re using the Java2D renderer, you can cast to PGraphicsJava2D, access the Graphics2D and do the same as https://github.com/processing/processing/blob/master/core/src/processing/awt/PGraphicsJava2D.java#L1358

1 Like