问题
I have following code, where closely mapped sprite, rectangle and polygon is been rotated at same angle in libgdx. After rotation rectangle is misaligned with the sprite. Although sprite is rotated when its drawn, the coordinates and dimensions stay same after the rotation. This is not the case for rectangle. Please see the code and results image below.
public void rotate(int angle){
System.out.println("Before-recta x , y " + this.rectangle.getX() + " " + this.rectangle.getY() + " " + this.rectangle.getHeight() + " " + this.rectangle.getWidth());
System.out.println("Before-sprite x , y " + sprite.getX() + " " + sprite.getY()+ " " + this.sprite.getHeight() + " " + this.sprite.getWidth());
this.sprite.rotate(angle);
this.rectangle = null;
this.polygon.rotate(angle);
this.rectangle = this.polygon.getBoundingRectangle();
System.out.println("Afer-sprite x , y " + sprite.getX() + " " + sprite.getY() + " " + this.sprite.getHeight() + " " + this.sprite.getWidth());
System.out.println("Afer-recta x , y " + this.rectangle.getX() + " " + this.rectangle.getY() + " " + this.rectangle.getHeight() + " " + this.rectangle.getWidth());
}
回答1:
If you look at the values for your rectangle the width is about 370 and the height is about 345. This is wider than it is taller. So when you rotate this you would expect it to be taller than it is wider. We'll do some quick match to see if what we're getting is correct:
We'll remove the width from the height to get the amount of extra space for both sides
370 - 346 = 24
Now we'll divide that by 2 as it's equally distributed to each side of the rectangle
24 / 2 = 12
we now take the original x position - 1/2 the extra value
268 - 12 = 256
And for the y position too
739 + 12 = 751
These match the values you are getting for x and y position for the rectangle so we know this is correct.
Now, if we do this for the Sprite you will see the value you are getting are not for the rotated sprite. The sprites before and after values are the same.
The reason for this is most likely that the sprite's x,y,w and h never change and instead a matrix is used to transform the image before rendering leaving the sprite with the original values throughout its lifetime.
来源:https://stackoverflow.com/questions/46601466/after-rotation-sprite-and-rectangle-position-misaligned-in-libgdx