簡體   English   中英

LibGdx Java中接近完美的碰撞

[英]Near perfect collision in LibGdx Java

我正在嘗試使游戲中的碰撞達到完美。 我正在測試的是,如果您與播放器撞牆,您會停下來。 我僅在玩家擊中牆的左側(牆在玩家的右側)時實現了碰撞代碼。 這是代碼。

    if(entityOnRight){
        if(player.getPositionCorner(SquareMapTuples.BOTTOM_RIGHT).x -
                ent.getPositionCorner(SquareMapTuples.BOTTOM_LEFT).x > -.9f)
            player.setMovementBooleans(false, false, false, false);
        else
            player.setMovementBooleans(true, false, false, false);
    }

注意:如果我走得很慢,它將使播放器停在我希望停止的位置,但是走得快,它將不會按照我想要的方式進行碰撞

本質上,代碼說明了牆壁是否在右側,它將檢查玩家矩形的右下角,減去牆壁的左下角,並檢查兩者之間的距離是否為0.001。 0.001幾乎是個不明顯的距離,因此為什么我使用該值。 這是player.setMovementBooleans的代碼

public void setMovementBooleans(boolean canMoveRight, boolean canMoveLeft, boolean canMoveUp, boolean canMoveDown){

    this.canMoveRight = canMoveRight;
    if(canMoveRight == false && moveRight)
        vel.x = 0;
}

Player類中的canMoveRight布爾值(而不是參數中的布爾值)使您能夠移動, moveRight是您嘗試向右移動時的狀態。 以下是一些可以更好地解釋這些布爾值如何交互的代碼:

//If you clicked right arrow key and you're not going 
    //Faster then the max speed

    if(moveRight && !(vel.x >= 3)){
        vel.x += movementSpeed;
    }else if(vel.x >= 0 && !moveRight){
        vel.x -= movementSpeed * 1.5f;
        System.out.println("stopping");
        //Make sure it goes to rest
        if(vel.x - movementSpeed * 1.5f < 0)
            vel.x = 0;
    }

和:

if(Gdx.input.isKeyPressed(Keys.D) && canMoveRight)
        moveRight = true;
    else
        moveRight = false;

因此,請單擊“ D”鍵以給出摘要,它可以讓您開始移動。 但是,如果布爾值canMoveRight為false,則不會移動您。 這是顯示發生情況的圖像(玩家是黃色,牆壁是綠色)

在此處輸入圖片說明

如您所見,播放器比我想要的遠了。 它應該在此時停止:

在此處輸入圖片說明

非常感謝您找出如何完成此操作的幫助!

處理這些沖突的最佳方法是使用已經隨Libgdx一起提供的物理引擎,例如Box2D。 當Box2D中發生沖突時,將觸發一個事件,您可以輕松地處理該事件。 因此,您可能應該在這里看看。

在沒有物理學的情況下實現此目標的另一種方法是使用表示玩家和牆壁的邏輯矩形(也可以是折線),並使用libgdx的Intersector類。 在這里

也許您嘗試的方法有點太復雜了:-)。 我建議從頭開始采用一種更簡單的方法:將地圖和播放器設為com.badlogic.gdx.math.Rectangle實例。 現在,在代碼的以下部分中,檢查移動之后玩家是否仍會在地圖內,如果可以,則允許移動,如果不允許,則不允許移動:

if(Gdx.input.isKeyPressed(Keys.D){
    float requestedX, requestedY;
    //calculate the requested coordinates
    Rectangle newPlayerPositionRectangle = new Rectangle(requestedX, requestedY, player.getWidth(), player.getHeight());
    if (newPlayerPositionRectangle.overlaps(map) {
        //move the player
    } else {
        //move the player only to the edge of the map and stop there
    }
}

暫無
暫無

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

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