Case example: Racer

A performance gain was found in Racer by altering the algorithm used. The game logic must ensure that the player drives through every gate in the track, and improving the gate boundary test algorithm improved the speed of the game.

The first implementation did this by calculating the shortest distance from the line between the gate boundaries to the center of the car. It is listed here:

public boolean isPointNear(double x, double y) {
    point_x = (int)x;
    point_y = (int)y;
    double line_x = 0;
    double line_y = 0;
    boolean ret = false;
    double xdiff = end_x - start_x;
    double ydiff = end_y - start_y;

    double u = ((x - start_x) * xdiff + (y - start_y) * ydiff) /(xdiff * xdiff + ydiff * ydiff);
    
    if (u < 0) {
        line_x = start_x;
        line_y = start_y;
    } else if (u > 1) {
        line_x = end_x;
        line_y = end_y;
    } else {
        line_x = (start_x + u * xdiff);
        line_y = (start_y + u * ydiff);
    }
    temp_x = (int) line_x;
    temp_y = (int) line_y;
    double xdiff2 = line_x - x;
    double ydiff2 = line_y - y;
    double length = Math.sqrt((xdiff2 * xdiff2 + ydiff2 * ydiff2));
    if (length <= LIMIT)
        ret = true;

    return ret;
}

However, in this case, maybe you don’t need that exact and complicated, mathematical algorithm. The next algorithm just checks if the car is inside a rectangle that is defined by the gate boundary points. It works well enough, plus it’s simpler and much faster.

public boolean isPointNear(int x, int y) {
    final int PADDING = 5;
    int rightX, leftX;
    int topY, bottomY;

    if (startX > endX) {
        rightX = startX + PADDING;
        leftX = endX - PADDING;
    } else {
        rightX = endX + PADDING;
        leftX = startX - PADDING;
    }
    if (startY > endY) {
        topY = startY + PADDING;
        bottomY = endY - PADDING;
    } else {
        topY = endY + PADDING;
        bottomY = startY - PADDING;
    }

    return x > leftX && x < rightX && y > bottomY && y < topY;
}