2
\$\begingroup\$

I have a character that starts in the air and applying gravity to it to collide with platforms in my level. At the start, the character gradually gains speed descending until it collides with a platform. After colliding, I display text letting me know if collision is detected (character touching the ground is true). But when I push the 'W' key, the character doesn't jump. It's worth noting that there is no dedicated ground zero as the level has platforms at different heights.

void Player::update(const std::vector<std::string>& layerData, float deltaTime)
{
    // check if player touches ground
    mOnGround = collideWithLevel(layerData);

    if (mInputManager->isKeyDown(SDLK_w)) // press W to jump
    {
        jump(deltaTime);
    }

    land(deltaTime);
}

void Player::jump(float deltaTime) // problem
{
    if (mOnGround)
    {
        mVelocity.y = mJumpPower * deltaTime;
        mOnGround = false;
    }
}


void Player::land(float deltaTime)
{
    if (!mOnGround)
    {
        mVelocity.y += mGravity * deltaTime;
        mPosition.y += mVelocity.y;
    }

    if (mOnGround)
        std::cout << "On ground" << std::endl; // fires
}
\$\endgroup\$
1
  • \$\begingroup\$ I take it the console log in Player::land(float) is called every frame after the player landed? Could you perhaps show your collideWithLevel() code? EDIT: Oh and your mJumpPower and mGravity numbers? Just to be sure. \$\endgroup\$
    – RdeGier
    Dec 13, 2015 at 12:53

2 Answers 2

1
\$\begingroup\$

you are probably checking for collisions after moving the player, so the character get's stucked in the ground, you have to check if there will be a collision before moving the player and move it if there's no collisions detected.

if(player.y - velocityY >= 0){
    player.y -= velocityY;
}else{
    player.y = 0;
}
\$\endgroup\$
1
\$\begingroup\$

It looks to me like you are not setting the velocity when jumping large enough (although this depends on mJumpPower and mGravity).

You jump function at the moment is,

void Player::jump(float deltaTime) // problem
{
    if (mOnGround)
    {
        mVelocity.y = mJumpPower * deltaTime;
        mOnGround = false;
    }
}

In this function you set that the horizontal velocity after a jump is proportional to deltaTime (which I assume is the time between frames or physics updates). To me this does not make sense as the velocity after a jump should be independent of the FPS or the physics update rate. Instead try something like this,

void Player::jump(float deltaTime) // problem
{
    if (mOnGround)
    {
        mVelocity.y = mJumpPower;
        mOnGround = false;
    }
}

If there is another reason for including this deltaTime then please feel free to correct me, however I cannot see what it is doing here.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .