I'm trying to create a simple car game with manual gear changes. However, I'm having a bit of trouble implementing the gear changes.
Here's my current code for the "car":
int gear = 1; // Current gear, initially the 1st
int gearCount = 5; // Total no. of gears
int speed = 0; // Speed (km/h), initially 0
int[] maxSpeedsPerGear = new int[]
{
40, // First gear max. speed at max. RPM
70, // Second gear max. speed at max. RPM
100, // and so on
130,
170
}
int rpm = 0; // Current engine RPM
int maxRPM = 8500; // Max. RPM
public void update(float dt)
{
if(rpm < maxRPM)
{
rpm += 65 / gear; // The higher the gear, the slower the RPM increases
}
speed = (int) ((float)rpm / (float)maxRPM) * (float)maxSpeedsPerGear[gear - 1]);
if(isKeyPressed(Keys.SPACE))
{
if(gear < gearCount)
{
gear++; // Change the gear
rpm -= 3600; // Drop the RPM by a fixed amount
if(rpm < 1500) rpm = 1500; // Just a silly "lower limit" for RPM
}
}
}
However, this implementation doesn't really work. The first gear works fine, but the following gear changes cause the speed drop. By adding some debugging messages, I get these speed values when changing at the RPM limit:
Speed at gear 1 before change: 40
Speed after changing from gear 1 to gear 2: 41
Speed at gear 2 before change: 70
Speed after changing from gear 2 to gear 3: 59
Speed at gear 3 before change: 100
Speed after changing from gear 3 to gear 4: 76
Speed at gear 4 before change: 130
Speed after changing from gear 4 to gear 5: 100
As you can see, the speed after each change is slower before the change. How would you take into consideration the speed before the gear change so that the speed wouldn't drop when changing gears?