2016-05-25 101 views
0

我試圖讓我的遊戲中的碰撞完全完美。我測試的是如果你與玩家撞牆,你會停下來。我只實現了當玩家擊中牆壁左側時(當牆位於玩家右側時)的碰撞代碼。這是代碼。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; 
} 

canMoveRight布爾在Player類(非參數)是什麼讓你能夠移動的代碼,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是假的,它不會移動你。這裏是在發生什麼事的圖像(該播放器是黃色的,牆是綠色的)

enter image description here

正如你可以看到,玩家走的更遠,那麼我想它。它應該停止在這一點上:

enter image description here

,首先要弄清楚如何做到這一點任何幫助,非常感謝!

回答

1

也許你試過的方式有點太複雜:-)。我建議從頭開始一個更簡單的方法:使地圖和播放器成爲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 
    } 
} 
+0

是但.overLaps方法是我要求的部分 – Luke

+0

所以它回答了你的問題? – WonderfulWorld

+0

對不起,我沒有意識到重疊是一種實際的內置方法 – Luke

1

處理這些碰撞的最好方法是使用像Box2D這樣的物理引擎,它已經與Libgdx打包在一起。當Box2D發生碰撞時,事件被觸發,您可以輕鬆處理該事件。所以你應該看看here

另一種實現此功能的方法是使用代表玩家和牆的邏輯矩形(也可以是折線)並使用Intersector類的libgdx。 這是here