2017-10-10 112 views
0

我想旋转一组精灵,多边形和矩形。图a)显示了2个精灵,边界多边形和矩形。该组围绕大矩形的中心旋转90度(两个矩形的联合)。在Libgdx中旋转后对齐精灵和有界矩形

以下代码创建图b)。它不会围绕联合矩形的中心旋转精灵和多边形。

public void rotate(int rangle, float rotateX, float rotateY){ 
    this.sprite.rotate(rangle); 
    this.polygon.rotate(rangle); 

    Polygon tempPoly = new Polygon(new float[] { 
      this.rectangle.x, this.rectangle.y, 
      this.rectangle.x, this.rectangle.y + this.rectangle.height, 
      this.rectangle.x + this.rectangle.width, this.rectangle.y + this.rectangle.height, 
      this.rectangle.x + this.rectangle.width, this.rectangle.y 
    }); 

    tempPoly.setOrigin(rotateX, rotateY); 
    tempPoly.rotate(rangle); 
    this.rectangle = null; 
    this.rectangle = tempPoly.getBoundingRectangle(); 


} 

下面的代码创建图c)。当我尝试将精灵和多边形移动到矩形位置时,会出现未命中对齐。

public void rotate(int rangle, float rotateX, float rotateY){ 

    this.sprite.rotate(rangle); 
    this.polygon.rotate(rangle); 

    Polygon tempPoly = new Polygon(new float[] { 
      this.rectangle.x, this.rectangle.y, 
      this.rectangle.x, this.rectangle.y + this.rectangle.height, 
      this.rectangle.x + this.rectangle.width, this.rectangle.y + this.rectangle.height, 
      this.rectangle.x + this.rectangle.width, this.rectangle.y 
    }); 

    tempPoly.setOrigin(rotateX, rotateY); 
    tempPoly.rotate(rangle); 
    this.rectangle = null; 
    this.rectangle = tempPoly.getBoundingRectangle(); 

    // This tries to move them to rectangle 
    this.sprite.setPosition(this.rectangle.getX(), this.rectangle.getY()); 
    this.polygon.setPosition(this.rectangle.getX(), this.rectangle.getY()); 

} 

enter image description here

的问题是如何旋转之后与矩形对齐的精灵(即类似于图一,在角度= 0)。 提示:出现此问题是因为在绘制小精灵时它们会进行旋转,因此精灵和矩形之间存在未命中对齐。 (link

回答

0

我必须从多边形旋转位置并使用矩形计算偏移量。然后将该偏移量添加到精灵和多边形。

public void rotate(int rangle, float rotateX, float rotateY){Rectangle pastRect = polygon.getBoundingRectangle(); 

this.sprite.rotate(rangle); 
this.polygon.rotate(rangle); 

Polygon tempPoly = new Polygon(new float[] { 
     this.rectangle.x, this.rectangle.y, 
     this.rectangle.x, this.rectangle.y + this.rectangle.height, 
     this.rectangle.x + this.rectangle.width, this.rectangle.y + this.rectangle.height, 
     this.rectangle.x + this.rectangle.width, this.rectangle.y 
}); 

tempPoly.setOrigin(rotateX, rotateY); 
tempPoly.rotate(rangle); 
Rectangle tempRect = new Polygon(polygon.getTransformedVertices()).getBoundingRectangle(); 
this.rectangle = tempPoly.getBoundingRectangle(); 

float x = sprite.getX() + (rectangle.x - tempRect.x); 
float y = sprite.getY() + (rectangle.y - tempRect.y); 
this.sprite.setPosition(x,y); 
this.polygon.setPosition(x,y); 
}