2012-10-23 156 views
4

我正在創建2D馬里奧遊戲。遊戲跳轉邏輯

以下功能旨在當按下特定按鍵來更新玩家的位置。玩家可以左右移動,跳到同一個地方,或跳到左邊或右邊(形成弧形)。

bool updatePlayerPosition(Movement* mov){ 
     if (this->keyPressed(SDLK_RIGHT)) { 
      mov->applyForce(1); // Changes the velocity in X 
     } 
     if (this->keyPressed(SDLK_LEFT)) { 
      mov->applyForce(-1); // Changes the velocity in X 
     }   
     if (this->keyPressed(SDLK_SPACE)) { 
      mov->jump();  // Changes the velocity in Y 
     }  
     if (this->keyPressed(SDLK_DOWN)) { 
      mov->fallDown(); // Changes the velocity in X and Y 
     } 

     Point* pos = mov->getPosition(); 

     // Check whether the position is out of bounds 
     if(Level::allowsMove(pos)){ 
       // If it is not, I update the player's current position 
       position->x = pos->x; 
       position->y = pos->y; 
       return true; 
     } 
     // If the movement is not allowed, I don't change the position 
     else { 
       mov->setPosition(*position); 
       return false; 
     } 
    } 

這裏是錯誤:當我打的水平(其中有一個固定的寬度)的結束,如果我試圖向右移動,並在同一時間跳,玩家跳躍,並保持在空氣。只有當我釋放空格鍵時,玩家纔會落地。

我該如何解決這個問題?

+0

一個建議:如果'是持久mov'不是必需的,只是把它定義在函數內部。 –

回答

2

對於您的遊戲,我認爲您只希望玩家在按下空間時跳躍當玩家在地板上時。然後你必須檢查球員是否在場上以獲得所需的行爲。

我建議你設備的機制是這樣的:

if (this->keyPressed(SDLK_SPACE) && this->isOnTheFloor()) { 
           ^^^^^^^^^^^^^^^^^^^^^^^ 
    mov->jump();  // Changes the velocity in Y 
}  
+0

'keyPressed(X)'返回'true'是鍵X被按下。 –

0

你的空格鍵處理程序應只適用力一次 - 上鍵不放,或向上,如果你喜歡,不是每一個幀。在空格鍵下,速度'上'應該被設置爲一些(可能是恆定的)值。然後,如果不是在地面上,則每個框架都應該以最大速度增加指定量。所以OnSpacebarDown, YVelocity = 10.0;併爲每個幀if(!bGrounded) YVelocity -= 1.0;