簡體   English   中英

libGDX:如何實現基於平鋪/網格的游戲角色運動?

[英]libGDX: How to implement a smooth tile / grid based game character movement?

因為害怕重新發明輪子,我想知道:

使用libGDX在自上而下的Tiled (2D)地圖上實現基於平滑網格的游戲角色移動的最佳方法是什么?

只要按下箭頭鍵(或者在角色的某個方向上發生觸摸事件),角色就應該在瓷磚之間保持平滑移動,並且應該完成限制在按鍵/觸摸釋放上的網格位置。 運動應獨立於幀速率。

我會很高興一些已經實現的示例可以研究並導致正確的libGDX API使用。

測試是否按下了特定按鈕(或觸摸屏幕),如果是,則在一個字段中設置正確的目標圖塊(玩家將要去的圖塊)並開始移動到那里,此運動僅在玩家處於下一個瓷磚。 當發生這種情況時,再次檢查輸入以保持移動(即重復)。

讓我們假設,您的圖塊寬度/高度為1,並且您希望每秒移動1個圖塊。 您的用戶按右箭頭鍵。 然后你只需將目標設置到玩家右側的方塊即可。

if(targettile!=null){
    yourobject.position.x += 1*delta;
    if(yourobject.position.x>=targettile.position.x){
        yourobject.position.x = targettile.position.x;
        targettile = null;
    }
}

此代碼僅針對右移動進行了簡化,您還需要將其用於其他方向。
如果玩家沒有移動,請不要忘記再次輪詢輸入。

編輯:

輸入密鑰輸入:

if (Gdx.input.isKeyPressed(Keys.DPAD_RIGHT)){

用於觸摸的InputPolling(cam是您的相機,touchPoint是用於存儲未投影觸摸坐標的Vector3,以及moverightBounds a(libgdx)Rectangle):

if (Gdx.input.isTouched()){
    cam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0));
    //check if the touch is on the moveright area, for example:
    if(moveRightBounds.contains(touchPoint.x, touchPoint.y)){
        // if its not moving already, set the right targettile here
    }
}

並且沒有人說過,你在渲染方法中得到delta作為參數,或者你可以在其他任何地方使用:

Gdx.graphics.getDeltatime();

參考文獻:

這僅適用於一個維度,但我希望您通過檢查方向鍵並添加/減去1然后將其轉換為int(或地板)來獲得該想法將為您提供下一個圖塊。 如果釋放密鑰,則仍然有未到達的目標,實體將繼續移動,直到達到目標磁貼。 我認為它看起來像這樣:

void update()(
    // Getting the target tile
    if ( rightArrowPressed ) {
        targetX = (int)(currentX + 1); // Casting to an int to keep 
                                       // the target to next tile
    }else if ( leftArrowPressed ){
        targetX = (int)(currentX - 1);
    }

    // Updating the moving entity
    if ( currentX < targetX ){
        currentX += 0.1f;
    }else if ( currentX > targetX ){
        currentX -= 0.1f;
    }
}

暫無
暫無

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

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