跳转时C ++ SDL Player不会掉线

时间:2016-11-13 22:05:11

标签: c++ sdl physics

我将尝试解释简单的,我的角色跳跃,但是当释放太空按钮时它不会掉落。我该如何解决?

这是跳转的代码:

if (keystate[keys[7]]) //Keys 7 = SPACE Button
{
    jumping = true; 
}
if (jumping) //If is jumping
{
    positionRect.y += jumpVel;
    jumpVel -= gravity;
    maxjumpheight++;
}

if (maxjumpheight >= 40)
{
    positionRect.y += maxjumpheight * delta; 

    std::cout << "maxjumpheight: " << maxjumpheight << std::endl;
    jumping = false;
    if (maxjumpheight == 40)
    {
        maxjumpheight == 0;
    }
}

Here是Player.cpp文件的全部来源!

2 个答案:

答案 0 :(得分:0)

如果你希望角色在你释放时停止跳跃。使用jumping = false将else添加到第一个if语句。

答案 1 :(得分:0)

处理这个问题的正常方法是给玩家一个y方向的速度脉冲和一些物理。如果jumpVel是y方向的速度,它会变为如下(我还会添加一些风格提示):

if (keystate[keys[7]]) //Keys 7 = SPACE Button
{
    jumping = true; 

    // unnecessary to set jumping to true and just check it directly afterwards. Just add it here instead

    jumpVel = 1.0; // Set this to some value, this is the impulse you give the player when he jumps
}

// Okay, time to update the position. Lets limit the player so he can't go below 0
if (positionRect.y > 0) {
    positionRect.y += jumpVel * delta; // This is how you calculate the new position given speed and change in time
}

// gravity affects the speed with which we fall
jumpVel -= 9.8 * delta;
像这样!现在,如果你拿着空格键,上面的实现允许玩家飞行,但如果你放手,你应该看到那个家伙掉下来。如果你想限制最大高度,我会把它留作练习。)

编辑:你的y轴是倒置的,所以我们必须相应地改变它:

if (keystate[keys[7]]) //Keys 7 = SPACE Button
{
    jumping = true; 
    jumpVel = 1.0;
}

// the character is above the bottom of the screen
if (positionRect.y > 480) {
    positionRect.y -= jumpVel * delta;
    //       note: ^ we just flip the axis
}
jumpVel -= 9.8 * delta;

EDIT2:好的,我们暂时跳过物理。实现所需行为的最简单方法是

if (positionRect.y > 0 && positionRect.y < 480) {
    // We are inside the screen bounds
    if (keystate[keys[7]]) {
        positionRect.y -= 1.0; // jump 
    } else {
        positionRect.y += 1.0; // fall
    }
}

删除jumping / falling / maxjumpheight标记。

EDIT3:啊,当然。让我们再修改一次。

if (keystate[keys[7]]) {
    if (positionRect.y > 0) positionRect.y -= 1.0; // jump if below the top
} else {
    if (positionRect.y < 480) positionRect.x += 1.0; // fall if above the bottom
}