如何在某处制作精灵点?

How to make a sprite point somewhere?

我不想让我的 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);
    }

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

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

基本上这减少到:

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

如果你想让你的精灵适合特定的旋转,请尝试使用 sprite.setRotation(float angle);

编辑

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

我想有一个像 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);
}