Hi!
I’m making a a top down car game (how original huh?) to teach myself some Java and game programming… it’s going ok so far (in fact, I’ve already made a lot more I ever thought I could pull off) but I’m now facing my biggest problem so far: collision detection.
I’m trying to use an Area made from the bounds of my car sprite, rotate it the same way as my sprite and move them together and then I would use the Area to check for collisions. My problem I guess is that I don’t really understand affine transformations, I originally just rotated the Image holding my sprite but as I started to realize I might have to go for Areas to get the collision detection working, I switched into using an AffineTransform to rotate my car.
I got it rotating the sprite correctly into the correct coordinates by trial and error but for some reason it’s not working for the Area - the Area rotates but the coordinates are no where near the car itself.
Here’s the code for my car’s draw method, I put the area code there as I’m already messing around with affinetransformations. If you forget about all the Area stuff, it works the way it should (i.e. it rotates the car correctly and draws it to the correct location). But the area gets drawn in funny places… the fact that I don’t understand my affine transformation code aside, I further don’t understand why it works for the sprite but not for the area…
// draw onto the Graphics2D object
public void draw(Graphics2D g) {
// create a new area from the sprite
carArea = new Area(getBounds());
// transformation, get the coords
AffineTransform atCar = new AffineTransform();
atCar.translate((int)this.getX(), (int)this.getY());
// rotate the sprite around the middle of the rear axel
atCar.rotate(
Math.toRadians((int)this.getRotation()),
this.getWidth() / 2,
this.getHeight() - (this.getHeight() / 4)
);
// apply the transformation to the area
carArea.transform(atCar);
// draw the readily rotated sprite
g.drawImage(this.sprite, atCar, null);
// visualize the Area
g.setColor(Color.red);
g.draw(carArea);
}
I don’t understand the translate part, but without that the sprite would be in funny places as well…
my getBounds
// get the car bounds
public Rectangle getBounds() {
return new Rectangle((int)getX(), (int)getY(), getWidth(), getHeight());
}
anything else from my crappy code you need to see, ask 8)