Stay on the track
Author: Bernhard Wymann
Keywords: torcs, berniw, bernhard wymann, robot, stability, stay, track

# 4.5 Stay on the Track ### Overview Now we make the car stay again on the track (at least on most of the tracks). We will introduce a margin around the middle of the track. When we are farther away from the middle we set the accelerator to zero. We will refine this by distinguish between inside and outside in the turns. When we are inside we can accelerate further, because the centrifugal force pushes the car outside. ### Implementation Here follows the implementation, put it in driver.cpp.
    /* Hold car on the track */
    float Driver::filterTrk(float accel)
    {
        tTrackSeg* seg = car->_trkPos.seg;

        if (car->_speed_x < MAX_UNSTUCK_SPEED) return accel;
If we are very slow do nothing. Then check if we are on a straight. If that's the case, check both sides.
        if (seg->type == TR_STR) {
            float tm = fabs(car->_trkPos.toMiddle);
            float w = seg->width/WIDTHDIV;
            if (tm > w) return 0.0; else return accel;
If we are in a turn check if we are inside or outside. If we are inside do nothing.
        } else {
            float sign = (seg->type == TR_RGT) ? -1 : 1;
            if (car->_trkPos.toMiddle*sign > 0.0) {
                return accel;
If we are outside and more than "w" from the middle away set accelerator to zero.
            } else {
                float tm = fabs(car->_trkPos.toMiddle);
                float w = seg->width/WIDTHDIV;
                if (tm > w) return 0.0; else return accel;
            }
        }
    }
We need to define WIDTHDIV in driver.cpp.
    const float Driver::WIDTHDIV = 4.0;    /* [-] */
Add the call in Driver::drive(). Change
                car->ctrl.accelCmd = filterTCL(getAccel());
to
                car->ctrl.accelCmd = filterTCL(filterTrk(getAccel()));
Finally we declare the new method and constant in driver.h.
            float filterTrk(float accel);
            static const float WIDTHDIV;
### Testdrive What you got till now is not too bad. You've written a robot that is able to master most of the tracks. We also reduced the lap times very much: mixed-2: 1:14:70, 0 damage. e-track-2: 1:24:45, 0 damage. e-track-4: 1:49:70, 0 damage. ### Downloads In case you got lost, you can download my robot for TORCS 1.2.0 or later. ### Summary You have implemented and understood an almost competitive robot. Congratulations:-)