I have a method to rotate a sprite's bounding box around the center of the sprite (the sprite rotates and I need the bounding box to rotate with it. The sprite is rectangular).
Instead of being rotated, the bounding box is skewing wierdly. When the angle is 0 - the bounding box is a perfect rectangle. But when the angle changes, the bounding box is getting gradually skewed.
All of this happens in the object's move()
method. This method is called every cycle of the game-loop. What I'm trying to do is this:
- Move the sprite in the direction the user chose. (x += dx, y += dy).
- Get the coordinates of the new center of the sprite.
- Get coordinates for the four vertices of the not-rotated-version of the sprite.
- Manipulate these coordinates, so they are now the vertices of the rotated sprite.
The coordinates that step 4 gives me, are used to create the bounding box (and temporarily draw it on the screen so I can see).
Somewhere, this fails. As I said, the bounding box doens't rotate. Instead, it skews (and maybe also rotates, not sure).
What could be the problem?
Code:
public void move(){
// Advance sprite.
x += dx;
y += dy;
// Get the new center point of the sprite.
centerx = x + width/2;
centery = y + height/2;
// Get the 4 vertices of the non-rotated version of the sprite.
xcoo[0] = (int) x;
xcoo[1] = (int) (x + width);
xcoo[2] = (int) (x + width);
xcoo[3] = (int) x;
ycoo[0] = (int) y;
ycoo[1] = (int) y;
ycoo[2] = (int) (y + height);
ycoo[3] = (int) (y + height);
// Manipulate each vertex, so it fits the rotated sprite.
for(int z=0;z<4;++z){
xcoo[z] -= centerx;
ycoo[z] -= centery;
xcoo[z] = (xcoo[z] * Math.cos(Math.toRadians(angle)) - ycoo[z] * Math.sin(Math.toRadians(angle)));
ycoo[z] = (xcoo[z] * Math.sin(Math.toRadians(angle)) + ycoo[z] * Math.cos(Math.toRadians(angle)));
xcoo[z] += centerx;
ycoo[z] += centery;
}
}
Help would be very appreciated. Thank you
ycoo[z] = (xcoo[z] * ...
uses thexcoo[z]
you modified the line before. Consider working on copies ofxcoo[z]
andycoo[z]
in the loop body and assign them out at the end of the iteration. \$\endgroup\$xcoo[z]
, since it's translating back to the origin. \$\endgroup\$xcoo[z]
from line 1, but line 4 gets thexcoo[z]
from line 3. The solution I intended to answer with before the question got prematurely locked was:{ auto x_rel = xcoo[z] - centerx, y_rel = ycoo[z] - centery; auto x_new = (x_rel * ..); auto y_new = (x_rel * ..); xcoo[z] = x_new + centerx; ycoo[z] = y_new + centery; }
\$\endgroup\$