c++ - 游戏跳转逻辑

标签 c++ algorithm sdl

我正在创建一个 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;
        }
    }

这是错误:当我到达关卡的尽头(具有固定宽度)时,如果我尝试向右移动并同时跳跃,玩家会跳跃并停留在空中。只有当我松开空格键时,玩家才会回到地面。

我该如何解决这个问题?

最佳答案

对于您的游戏,我认为您只希望玩家在按下空格时在玩家在地板上时跳跃。然后,您必须检查玩家是否在场上以获得所需的行为。

我建议你设置这样的机制:

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

关于c++ - 游戏跳转逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13023652/

相关文章:

algorithm - 检查给定的字符串是否可以由从杂志文章中剪下的一组字符创建

c++ - SDL + OpenGL : access violation when creating buffer

c++ - 导致未定义行为的悬挂引用

c++ - 理解指针c++

algorithm - 数组中任意 k 个元素的数字之和

c - SDL "dropping"初始事件?

c++ - 使用并行处理在 C++ 中制作游戏

c++ - 准确计算 1 到 10 之间的值的谐波数

c++ - 将基本(非指针)参数设为 const 是否有意义?

c++ - 优先级队列和堆之间的区别