c++keyboard-eventsogre3dacceleration

How do you gradually accelerate an object based on button press (Ogre3D)?


I currently have an object that I want to gradually accelerate. The longer you hold down on a certain key, the faster it goes. I managed to get it to work fine for one key (when it moves right) however, it does not seem to work for the other directions.

The code I have right now is:

    if (mKeyboard->isKeyDown(OIS::KC_NUMPAD8)) 
    {
        mSpeed += mAcceleration*evt.timeSinceLastFrame;
        movement.z -= mSpeed*evt.timeSinceLastFrame;
        mAcceleration++;
    }
    if (mKeyboard->isKeyDown(OIS::KC_NUMPAD4)) 
    {
        mSpeed += mAcceleration*evt.timeSinceLastFrame;
        movement.x -= mSpeed*evt.timeSinceLastFrame;
        mAcceleration++;
    }
    if (mKeyboard->isKeyDown(OIS::KC_NUMPAD5)) 
    {
        mSpeed += mAcceleration*evt.timeSinceLastFrame;
        movement.z += mSpeed*evt.timeSinceLastFrame;
        mAcceleration++;
    }
    if (mKeyboard->isKeyDown(OIS::KC_NUMPAD6))
    {
        mSpeed += mAcceleration*evt.timeSinceLastFrame;
        movement.x += mSpeed*evt.timeSinceLastFrame;
        mAcceleration++;
    }

And the statement that works fine is the last one. The rest just move normally, without any acceleration.

I was wondering how I can get the object to gradually accelerate at the other directions as well.

P.S Just in case anyone is wondering as well, I cannot change the "if"s to "while". The program does not run at all when I change it.

P.P.S The object works (gradually accelerates in all directions) when I change the others to "else if" however, I can no longer move diagonally which is also my problem. I have tried doing something such as

else if (mKeyboard->isKeyDown(OIS::KC_I) && mKeyboard->isKeyDown(OIS::KC_J))
    {
        mSpeed += mAcceleration *evt.timeSinceLastFrame;
        movement.z -= mSpeed*evt.timeSinceLastFrame;
        movement.x -= mSpeed*evt.timeSinceLastFrame;
        mAcceleration++;
    }

but it still does not move diagonally.


Solution

  • So apparently, I just needed to add another if statement

    if (!mKeyboard->isKeyDown(OIS::KC_NUMPAD8) && !mKeyboard->isKeyDown(OIS::KC_NUMPAD4) && !mKeyboard->isKeyDown(OIS::KC_NUMPAD6) && !mKeyboard->isKeyDown(OIS::KC_NUMPAD2))
    {
        mSpeed = mSetSpeed;
        mAcceleration = mSetAcceleration;
    }
    

    (I know it looks bad ahahaha) to reset the speed and acceleration back to normal (so it can gradually increase again) when it is no longer being pressed. Still curious as to why it won't work without mAcceleration++ though.

    Another way of solving this is having

    if(movement.length()==0) mSpeed = mSetSpeed;
    else mSpeed += mAcceleration*evt.timeSinceLastFrame;