2016-08-06 70 views
0

我是新來的Slick2D,我正在嘗試運用我的角色。我可以在按住移動鍵的同時使其平穩移動,但我也希望角色完成移動,以便它完全停在下一個圖塊上(我的地圖簡單,圖塊爲32x32)。這對我來說是一個問題,因爲它會移動到下一個瓷磚,但它傳送到那裏 - 移動是即時的,我希望我的角色以相同的速度繼續其移動。如何讓字符在Slick2D釋放鍵後繼續移動?

我試過例如這樣的事情在我update()方法:

else if (input.isKeyPressed(Input.KEY_D)) 
    { 
     characterAnimation = characterAnimationRight; 
     characterAnimation.update(delta); 
     xCoord = (int) xCoord; 
     while (xCoord%32 != 0) 
     { 
      xCoord += 1; 
      characterAnimation.update(delta); 
      if (xCoord > Window.WIDTH - 32) 
      { 
       xCoord = Window.WIDTH - 32; 
      } 

     } 
    } 

,但我不能讓它工作。

回答

0

解決方法是不計算update()方法中xCoordwhile()。原因在於它是在update()方法的單次運行中計算的,之後調用render()方法來渲染字符。這意味着角色在while()之後呈現並傳送。

這裏是我的解決方案:

@Override 
public void update(GameContainer gc, StateBasedGame s, int delta) 
     throws SlickException { 

    // ....... 

    if (moving) 
    { 
     if (movingDirection == DIR_RIGHT) 
     { 
      if (xCoord >= targetCoord) 
      { 
       xCoord = targetCoord; 
       moving = false; 
      } 
      else 
      { 
       xCoord += delta * 0.1f; 
       characterAnimation.update(delta); 
       if (xCoord > Window.WIDTH - 32) 
       { 
        xCoord = Window.WIDTH - 32; 
       } 
      } 
     } 
     else if (movingDirection == DIR_LEFT) 
     { 
      if (xCoord <= targetCoord) 
      { 
       xCoord = targetCoord; 
       moving = false; 
      } 
      else 
      { 
       xCoord -= delta * 0.1f; 
       characterAnimation.update(delta); 
       if (xCoord < 0) 
       { 
        xCoord = 0; 
       } 
      } 
     } 
     else if (movingDirection == DIR_UP) 
     { 
      if (yCoord <= targetCoord) 
      { 
       yCoord = targetCoord; 
       moving = false; 
      } 
      else 
      { 
       yCoord -= delta * 0.1f; 
       characterAnimation.update(delta); 
       if (yCoord < 0) 
       { 
        yCoord = 0; 
       } 
      } 
     } 
     else if (movingDirection == DIR_DOWN) 
     { 
      if (yCoord >= targetCoord) 
      { 
       yCoord = targetCoord; 
       moving = false; 
      } 
      else 
      { 
       yCoord += delta * 0.1f; 
       characterAnimation.update(delta); 
       if (yCoord > Window.WIDTH - 32) 
       { 
        yCoord = Window.WIDTH - 32; 
       } 
      } 
     } 
    } 
} 

可變moving設置按移動鍵後真。現在,在render()的每次調用之後,字符在update()中移動一點,然後在此新位置呈現,直至完全位於圖塊上。

0

爲什麼不嘗試使用「xSpeed」和「ySpeed」並根據'characterAnimation'設置的位置設置這些值,並確定您是否在精確的瓷磚上?

喜歡的東西:

else if (input.isKeyPressed(Input.KEY_D)) { 
    characterAnimation = characterAnimationRight; 
} 

// ... 

if (characterAnimation == characterAnimationRight){ 
    xSpeed = 1; 
} 
else if (characterAnimation == characterAnimationLeft){ 
    xSpeed = -1; 
} 
xCoord += xSpeed; 
characterAnimation.update(delta); 
if(xCoord % 32 == 0) { 
    xSpeed = 0; 
} 
// ... 

我真的不知道你的代碼(或slick2d)是如何工作的,所以我假定xCoord值神奇地考慮到當characterAnimation.update(delta)被調用。否則根據xCoord做任何你需要的來更新角色的位置。

相關問題