如何在Slick2D中从中心绘制旋转图像?

时间:2015-10-02 13:30:09

标签: java image slick2d image-rotation

问题如下: 我有一个位置让我们说一个宇宙飞船,位置必须在它的中间定义(例如由于碰撞问题等)。如果太空飞船不会旋转,图像将如下绘制:

spaceship.draw(xPos - width/2 , yPos - height/2);

宇宙飞船现在是Slick2D中的Image,它具有随机角度(0 <=角度<360),并且仍然必须在其中心定义位置。 draw()中的方法是什么 - 方法如下:

enter image description here 它在图像周围绘制一个椭圆形(我猜可能具有尽可能小的表面区域),然后查看距离中心135°处的线切割椭圆(红点)并将其设置为位置。

我仍然希望将其绘制为居中,这意味着,我必须在两个维度中减去一个值(draw(xPos - xOff, yPos - yOff)):

enter image description here

但我无法计算出来!有谁可以帮助我吗?我浪费了两天才明白问题是什么......

非常感谢Greets, [R

这里是渲染代码:

> public void render(GameContainer gc, StateBasedGame sbg, Graphics g)
> throws SlickException{
>           
>           // This sets all rotation to the middle of the graphics.
>           // The method works RELATIVE TO THE TOP-LEFT-CORNER OF THE IMAGE.
>           skin.setCenterOfRotation(skin.getWidth() * Revolve.getGS()/2 + Revolve.getXShift(),
>                   skin.getHeight() * Revolve.getGS()/2 + Revolve.getYShift());
>           
>           // This sets the Angle properly
>           skin.setRotation(angle);
>           
>           // This draws the image: xPos and yPos define THE CENTER of the Image.
>           skin.draw(
>               (float) (Revolve.getXShift() + Revolve.getGS() * xPos),
>               (float) (Revolve.getYShift() + Revolve.getGS() * yPos),
>               Revolve.getGS()
>           );
>     
>           // Draws the xPos and yPos of the Ship
>           g.setColor(Color.white);
>           g.drawOval(Revolve.getXShift() + Revolve.getGS() * xPos, Revolve.getYShift() + Revolve.getGS() * yPos, 2, 2);
>       }

1 个答案:

答案 0 :(得分:1)

一些代码都清楚了。

这是一个解决方案:

@Override
public void init(GameContainer container) throws SlickException
{
    this.character = new Image("/home/ronan/Images/20150517010612.jpg");
    this.scale = 0.5f;
    // When you set your center of rotation is is relative to your image ONLY.
    // this will make the center of my image to be the center of the rotation
    // NOTHING more to add
    this.character.setCenterOfRotation((this.character.getWidth()/2)*this.scale, (this.character.getHeight()/2)*this.scale);
}

@Override
public void update(GameContainer container, int delta) throws SlickException
{
    this.rotation +=delta/10;
    this.character.setRotation(this.rotation);
}

public void render(GameContainer container, Graphics g) throws SlickException
{
    // Here I consider that my position is (500,500). then to draw it, I just substract hal the size of my image.
    // It will draw from top-lefft corner but based on my center.
    character.draw(500-(this.character.getWidth()/2)*this.scale, 500 - (this.character.getHeight()/2)*this.scale,this.scale);
}

我将所有内容分开来清楚。

init方法中,您必须设置旋转中心。此中心相对于图像,因此只需将宽度广告高度除以2即可得到图像中心的坐标。当它工作时,你乘以你的比例。没有什么可以添加的,因为它对您的图像来说真的是本地的。

在渲染方法中,始终从左上角绘制图像。只需减去半宽和半高即可设置使用您的中心。

只需将此代码改编为您的代码即可。询问您是否需要更高的精确度。

enter image description here enter image description here