簡體   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