Working on a simple Java 2D game. A tank is controlled by the user. It can be rotated in any angle, and it moves in the direction of that angle.
I'm making a bounding box for the tank, so later I can add collision detection. Currently, I have the box following the sprite wherever it goes, but it doesn't rotate when the sprite rotates. I tried to add code to make the box rotate with the sprite, but adding this code simply makes the bounding box go crazy. It doesn't appear as a box anymore, more like a line just flickering and moving around.
(Obviously the bounding box should be invisible, but for now I'm drawing it on the screen to check for problems).
xcoo[]
and ycoo[]
are both of type double
and hold four values each. These values are the coordinates of the four vertices of the bounding box (a rectangle-shaped Path2D
).
(Please note that an actual bounding box is only created when it needs to be drawn on the screen, or in collision detection which I haven't written yet. Most of the time, it's just coordinates.)
The Tank's move()
method is called every cycle of the game-loop.
The move()
method updates the location of the sprite, and the location of the bounding box. This works fine. But as I said, trying to rotate the bounding box in that method (aka manipulate it's vertices using the rotation matrix), makes it go
Here is the Tank
's move()
method:
public void move(){
// Updates the location of the sprite. (works)
x += dx;
y += dy;
bbCenterX += dx;
bbCenterY += dy;
// Updates the location of the bounding box. (works)
for(int i=0;i<4;i++){
xcoo[i] += dx;
ycoo[i] += dy;
}
// Should rotate the bounding box (aka, manipulate it's coordinates
// so when it is created with these coordinates, it's rotated).
// (Doesn't work).
for(int z=0;z<4;z++){
xcoo[z] = xcoo[z] - bbCenterX;
ycoo[z] = ycoo[z] - bbCenterY;
xcoo[z] = ((xcoo[z] * Math.cos(angle)) - (ycoo[z] * Math.sin(angle)));
ycoo[z] = ((xcoo[z] * Math.sin(angle)) + (ycoo[z] * Math.cos(angle)));
xcoo[z] = xcoo[z] + bbCenterX;
ycoo[z] = ycoo[z] + bbCenterY;
}
}
What's wrong with my rotation? I suspect that that's the part of the code where the problem is, but if you think differently, please tell me to post more code.
Thanks a lot