Search code examples
c++game-physics

Creating acceleration of an object (tank) in a game


I'm having a trouble with making my Tank accelerate when I press a move button and decelerate when I let go of it. Don't be too harsh on me for not being a pro because I'm still learnig and Thanks in advance!

I also have variables called 'speed' and 'maxspeed' which I played around with and it didn't turn out to well, and the code below basicaly makes my tank move in an update function

if(TestName->Tank[0].up == true){
            TestName->Tank[0].position_y = TestName->Tank[0].position_y + (TestName->Tank[0].speed +     0.06f);
        }
        if(TestName->Tank[0].down == true){
            TestName->Tank[0].position_y = TestName->Tank[0].position_y - 0.06f;
        }
        if(TestName->Tank[0].right == true){
            TestName->Tank[0].rotation = TestName->Tank[0].rotation + 0.6f;
        }
        if(TestName->Tank[0].left == true){
            TestName->Tank[0].rotation = TestName->Tank[0].rotation - 0.6f;
        }
}

Solution

  • In this bit of code:

    TestName->Tank[0].position_y = TestName->Tank[0].position_y + (TestName->Tank[0].speed +     0.06f);
    

    it looks horribly like you are trying to add an acceleration (0.06) to your speed while at the same time adding the speed to the position. The plus sign won't change the speed, it will just calculate the result and use it in the equation.

    Do it in two steps:

    TestName->Tank[0].speed += 0.06f;
    TestName->Tank[0].position_y += TankName->Tank[0].speed;
    

    When you have that bit working your next issue will be inability to steer. I think you would be well advised to google vectors (maths, not C++) and the difference between velocity and speed.