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[3];
int[] yPoints = new int[3];
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.