如何在某处制作精灵点?

时间:2015-07-25 14:42:04

标签: java rotation libgdx sprite

我想让我的精灵指向光标,我该如何计算旋转它需要多少?

//First is get the cursor position
x=Gdx.input.getX();
y=Gdx.input.getY();

//then rotate the sprite and make it point where the cursor is
Sprite.rotate(??);

更新 - > 我尝试了这个但是我不知道当它指向正确的方向时它应该停止旋转的条件

double radians = Math.atan2(mouseY - spriteY, mouseX - spriteX)
float fl=(float)radians;

Sprite.rotate(fl)

更新2 - > 当我这样做时它几乎不动:

public void update(){
        int x=Gdx.input.getX();
        int y=Gdx.input.getY();

        double radians=Math.atan2(y-Spr.getY(),x-Spr.getX());
        float angle=(float)radians;
        Spr.setRotation(angle);
    }

更新3 - >所以现在我认为它跟随光标,但它使用了精灵的相反部分,想象一个箭头,而不是使用箭头的尖头部分指向它使用箭头的另一侧,希望你明白我的意思,顺便说一句,这就是我所做的:

 public void update(){
        int x=Gdx.input.getX();
        int y=Gdx.graphics.getHeight()-Gdx.input.getY();

        double radians= Math.atan2(y - launcherSpr.getY(), x - launcherSpr.getX());
        float angle=(float)radians*MathUtils.radiansToDegrees; //here
        launcherSpr.setRotation(angle);
    }

2 个答案:

答案 0 :(得分:2)

您可以使用Math.atan2(double y, double x)获得所需的效果。

此方法计算极坐标中的角度,假设您在(0,0)处有一个点而在给定(xo,yo)处有另一个点。因此,要使其工作,您必须规范化值,以便原点是精灵的位置,(xo,yo)是鼠标相对位置的比较。

基本上这减少到:

double radians = Math.atan2(mouseY - y, mouseX - x)

答案 1 :(得分:1)

如果您希望将精灵适合某个轮换,请尝试使用sprite.setRotation(float angle);

修改

我不知道rotate()是否会向实际添加旋转,如果是这种情况,每次调用此方法时,您的对象都会旋转。尝试使用setRotation(),但请记住,它适用于度数,而某些方法(如MathUtils.atan2())会返回弧度值,因此您必须将该结果转换为度数。

我想有一个像MathUtils.toDegrees()MathUtils.radiansToDegrees()这样的功能可以帮助你达到这个目的。

编辑2

可能发生的另一个问题是input.getY()被反转,所以(0,0)位于左上角。

正确的方法应该是这样的:

public void update(){
    int x = Gdx.input.getX();
    int y = HEIGHT - Gdx.input.getY(); 
    // HEIGHT is an static user variable with the game height

    float angle = MathUtils.radiansToDegrees * MathUtils.atan2(y - Spr.getY(), x - Spr.getX());
    Spr.setRotation(angle);
}