Acceleration problems

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

        if(gas){
speed += 3;
}else if(break_ && !(speed < 6)){
speed -= 3;
}else if(!break_ && !gas && !(speed < 6)){
speed -= 0.3;
}else{
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.

• Quick tip: cars have "brakes" not "breaks". So your variable can be called "brake" and you don't need the underscore after it. :) – Almo Nov 4 '15 at 20:18
• 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 – Richard Tingle Nov 4 '15 at 20:19
• What is this >6 stuff? – jgallant Nov 4 '15 at 20:27
• Jon it is to prevent the speed from going below 6 – Zoe the transgirl 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

if(gas){
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;

• The position.axis change should also be multiplied by delta. Other than that; exactly this – Richard Tingle Nov 4 '15 at 20:22
• 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 – Zoe the transgirl Nov 4 '15 at 20:28
• @Polarbear0106 gamedev.stackexchange.com/a/56993/10728 typically you would use a framework/engine, which takes care of this stuff for you ;) – jgallant Nov 4 '15 at 20:46