1
votes

I'm fairly new to programming and i'm trying to make a little game where you can control(rotate) a tank and different guns on top of the tank indepently. (I'm using slick)

during tank rotation the guns should rotate around the center of the tank-image because they are attached.

public void drawTankandGuns(){
  tankImage.draw(position.x, position.y);
  gunImage.draw(position.x+canonOffsetX, position.y+canonOffsetY);
}

public void rotateDuringMovement(){
  gunImage.setCenterOfRotation(tankImage.getWidth/2-gunOffsetX,
    tankImage.getHeight/2-gunOffsetY);

  gunImage.rotate(angle);
  tankImage.rotate(angle);
}

which works fine so far. gun is attached and rotates with tank. but if i want to rotate the gun without the tank (and tank is rotated already) and set the center of rotation back to the gun the gun-image is drawn back at its original position losing the position from the rotation around the tank...

edit: the solution was to use a different approach. draw the gunImage dependend on sin/cos of the tankImage rotation.

1
If you found a solution to your problem, go ahead and submit an answer for it. You can mark is as the answer. - Qix - MONICA WAS MISTREATED

1 Answers

1
votes

the solution was to use a different approach. draw the gunImage dependend on sin/cos of the tankImage rotation.

//calculate the gun position on top of the tank
gunPosX = tankPosX + gunPosOffsetX;
gunPosY = tankPosY + gunPosOffsetY;

//calculate the tank rotation center
tankRotationsCenterX = tankPosX + tankImage.getCenterOfRotationX();
tankRotationsCenterY = tankPosY + tankImage.getCenterOfRotationY();

//calculate distance between gun position and tank rotation center
dx = tankRotationsCenterX - gunPosX ;
dy = tankRotationsCenterY - gunPosY ;
dis = Math.sqrt(dx * dx + dy * dy);

//calculate the offset based on the rotation of the tank
//rotation offset for the gun placement
gunRotaOff = 20;

gunX_offset = dis*Math.cos(Math.toRadians(tankImage.getRotation()+gunRotaOff));
gunY_offset = dis*Math.sin(Math.toRadians(tankImage.getRotation()+gunRotaOff));

gunXhalf = gun.getImage().getWidth() / 2;
gunYhalf = gun.getImage().getHeight() / 2;

//draws the gun dependend on the ship position and the ship rotation
//don't forget to subtract half the width/height for exact positioning
gun.drawIngame(tankRotationsCenterX - gun_x_offset)-gunXhalf , (tankRotationsCenterY - gun_y_offset) - gunYhalf ));