Im trying to make a car game, but i cannot get the acceleration code right. With this code:

        speed += 3;
    }else if(break_ && !(speed < 6)){
        speed -= 3;
    }else if(!break_ && !gas && !(speed < 6)){
        speed -= 0.3;
        speed = 6;

it is up on 1000 within 5 secounds. I tried multiplying it with smaller numbers, but it still doesnt work(in fact it got worse). So, how can this be improved so it has reasonable parameters? Asof the maximum speed, i can implement that on my own.

  • 2
    \$\begingroup\$ Quick tip: cars have "brakes" not "breaks". So your variable can be called "brake" and you don't need the underscore after it. :) \$\endgroup\$ – Almo Nov 4 '15 at 20:18
  • 2
    \$\begingroup\$ Do you have any concept of a frame time. Or change per second. I expect your loop is freewheeling as fast as it can. Hence the issue. Always measure frame time and multiply it by a rate of change to get actual change \$\endgroup\$ – Richard Tingle Nov 4 '15 at 20:19
  • \$\begingroup\$ What is this >6 stuff? \$\endgroup\$ – jgallant Nov 4 '15 at 20:27
  • \$\begingroup\$ Jon it is to prevent the speed from going below 6 \$\endgroup\$ – user69046 Nov 4 '15 at 20:30

Try adding in a Velocity variable. But more importantly, you need to keep track of your deltaTime, which is the time that elapsed since your last frame.

More than likely the framework you are using has this, if not you will need to implement one.

float Velocity;
float Speed = 3;     //Your speed could vary here

   Velocity += Speed * deltaTime;     //when gas is pressed, speed up
else if (brake && (Velocity > 6)) {
   Velocity -= Speed * deltaTime;      //When brakes are pressed, slow down
else if(!brake && !gas && (Velocity > 6)){
   Velocity -= Speed * deltaTime;     //friction should be a different value than Speed
else {
    Velocity = 6;

//Update the position
Position.Axis += Velocity;
  • \$\begingroup\$ The position.axis change should also be multiplied by delta. Other than that; exactly this \$\endgroup\$ – Richard Tingle Nov 4 '15 at 20:22
  • \$\begingroup\$ The speed determines how quick the stripes moves(everything else stands still). However, how do i get the delta time? Im using Android, but it should be the same as normal Java \$\endgroup\$ – user69046 Nov 4 '15 at 20:28
  • 1
    \$\begingroup\$ @Polarbear0106 gamedev.stackexchange.com/a/56993/10728 typically you would use a framework/engine, which takes care of this stuff for you ;) \$\endgroup\$ – jgallant Nov 4 '15 at 20:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy