簡體   English   中英

將精靈移動到鼠標單擊[Libgdx];

[英]Move sprite to mouse click [Libgdx];

我是libgdx游戲編程的新手,我想創建一個RPG類型的游戲。

我想讓玩家朝着鼠標/觸摸位置移動。

我已經計算出了這樣做的合理方法,但似乎玩家一次只能移動一幀,這意味着玩家需要多次點擊才能到達正確的位置,而不是走到點擊位置框架框架只需點擊一下即可。

我的代碼:

Gdx.input.setInputProcessor(new Input(){
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        projected = new Vector3(screenX, screenY, 0);
        cam.unproject(projected);

        if(projected.x != position.x || projected.y != position.y){
            float pathX = projected.x - position.x;
            float pathY = projected.y - position.y;

            float distance = (float) Math.sqrt(pathX * pathX + pathY * pathY);
            float directionX = pathX / distance;
            float directionY = pathY / distance;

            position.x += directionX * Speed;
            position.y += directionY * Speed;
        }

        return true;
    }

每次觸摸屏幕時都會調用您的方法(一次)。 您的方法更改位置(一次)

position.x += directionX * Speed;
position.y += directionY * Speed;

所以每次觸摸屏幕只會移動你的精靈一次。

Screen類有一個方法render(float deltaTime) 這會被重復調用,參數給出自上次調用以來的時間。 這使得它成為一種有用的方法,可以執行需要重復發生的事情(比如更新精靈的位置)。

所以你真正想要在touchDown()是設置你的Sprite方向(作為Sprite對象中包含的字段)。 然后你可以編寫類似的方法

update(float deltaTime) {
   position.x += directionX * Speed * deltaTime;
   position.y += directionY * Speed * deltaTime;
}

在你的精靈課程中。 這幾乎就是你所寫的,但* deltaTime確保位置改變的量只是自上次調用此方法以來所覆蓋的距離。

此方法仍然永遠不會被調用,因此您需要從Screen.render(deltaTime)方法調用它:

render(float deltaTime) {
   mySprite.update(deltaTime);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM