繁体   English   中英

如何在某处制作精灵点?

[英]How to make a sprite point somewhere?

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

//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()返回弧度值,因此您必须将该结果转换为度。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM