The updateRectLocation() function

The code related to collision detection and the Rect movement is handled in the updateRectLocation() function, which is shown as follows:

/**
* Updates the rectangle location by +/- 1px in the x or y based on
* the current location.
*/
void updateRectLocation() {
// Determine if the bounding rectangle has "bumped" into either
// the left/right side or top/bottom side. Depending on which side,
// flip the direction:
int xBouncePoint = bounds.width - rect.width;
if (rect.x == xBouncePoint) rect.horizDir = 'L';
if (rect.x == 0) rect.horizDir = 'R';

int yBouncePoint = bounds.height - rect.height;
if (rect.y == yBouncePoint) rect.vertDir = 'U';
if (rect.y == 0) rect.vertDir = 'D';

// If the direction has changed based on the x and y
// coordinates, ensure the x and y points update
// accordingly:
int horizIncrement = 1;
if (rect.horizDir == 'L') horizIncrement = -1;
rect.x = rect.x + horizIncrement;

int vertIncrement = 1;
if (rect.vertDir == 'U') vertIncrement = -1;
rect.y = rect.y + vertIncrement;
}

The primary difference between this code and the code we wrote in Chapter 5Creating and Loading a WebAssembly Module, is the collision detection logic. Instead of simply tracking the location of the rect instance horizontally and changing direction when it hits the right boundary, the function now tracks the horizontal and vertical directions and manages each independently. Although this isn't the most performant algorithm, it does achieve the goal of ensuring the spaceship changes direction when it encounters the edge of the <canvas>.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset