I'm trying to make a game like Tank Trouble.
The problem is that when I'm trying to rotate and draw a tank picture, all other tanks pictures will be rotated.
Here is my code:
// draw tanks
ArrayList<Tank> tanks = new ArrayList<>();
tanks.addAll(TankTroubleMap.getAITanks());
tanks.addAll(TankTroubleMap.getUserTanks());
for (Tank tankToDraw : tanks) {
g2d.rotate(-Math.toRadians(tankToDraw.getAngle())
, tankToDraw.getCenterPointOfTank().getXCoordinate()
, tankToDraw.getCenterPointOfTank().getYCoordinate());
g2d.drawImage(tankToDraw.getTankImage()
, (int) tankToDraw.getCenterPointOfTank().getXCoordinate() - Constants.TANK_SIZE / 2
, (int) tankToDraw.getCenterPointOfTank().getYCoordinate() - Constants.TANK_SIZE / 2
, Constants.TANK_SIZE, Constants.TANK_SIZE, null);
}
You simply need to counter-rotate graphics back once you've drawn the image you wanted to rotate. Otherwise the same rotation will be applied to everything painted past the point you applied the rotation at.
So in your case:
for (Tank tankToDraw : tanks) {
g2d.rotate(-Math.toRadians(tankToDraw.getAngle())
, tankToDraw.getCenterPointOfTank().getXCoordinate()
, tankToDraw.getCenterPointOfTank().getYCoordinate());
g2d.drawImage(tankToDraw.getTankImage()
, (int) tankToDraw.getCenterPointOfTank().getXCoordinate() - Constants.TANK_SIZE / 2
, (int) tankToDraw.getCenterPointOfTank().getYCoordinate() - Constants.TANK_SIZE / 2
, Constants.TANK_SIZE, Constants.TANK_SIZE, null);
g2d.rotate(Math.toRadians(tankToDraw.getAngle())
, tankToDraw.getCenterPointOfTank().getXCoordinate()
, tankToDraw.getCenterPointOfTank().getYCoordinate());
}
Any transformations (in this case - rotation) you apply to graphics are preserved for all future operations you perform on that graphics instance, including further transformations. You have to remember that when working with graphics.