liveBook · Manning

Brute-force distance check

As explained in High Performance Unity Game Development

A collision-checking technique that tests distances between every pair of entities directly.

When enemies overlap in a survival game, check each pair’s distance and push overlapping enemies apart. This direct approach avoids spatial partitioning, keeping the implementation simple. section 4.4.7

Compare squared distance with the squared sum of the enemies’ radii to avoid calculating a square root. For an overlap, find the midpoint and move the enemies in opposite directions until they are separated. section 4.4.7

Listing 4.15 Enemy-to-enemy collision detection and response
static void doEnemyToEnemyCollision(GameData gameData, Balance balance)
{
    float diameter = balance.EnemyRadius + balance.EnemyRadius;
    float diameterSqr = diameter * diameter;
    for (int enemyIdx1 = 0; enemyIdx1 < balance.NumEnemies; enemyIdx1++)
    {
        for (int enemyIdx2 = enemyIdx1 + 1; enemyIdx2 < balance.NumEnemies; enemyIdx2++)
        {
            Vector2 diff = gameData.EnemyPosition[enemyIdx1] - 
                           gameData.EnemyPosition[enemyIdx2];
            if (diff.sqrMagnitude <= diameterSqr)
            {
                Vector2 diffNormalized = diff.normalized;
                Vector2 midPoint = (gameData.EnemyPosition[enemyIdx1] + 
                                    gameData.EnemyPosition[enemyIdx2]) / 2.0f;
                gameData.EnemyPosition[enemyIdx1] = midPoint + 
                                                    diffNormalized * 
                                                    balance.EnemyRadius;
                gameData.EnemyPosition[enemyIdx2] = midPoint - 
                                                    diffNormalized * 
                                                    balance.EnemyRadius;
            }
        }
    }
}

The nested loops check each enemy pair once, then use squared distance to detect overlap and reposition the pair. section 4.4.7

How High Performance Unity Game Development covers it

How deep it goes
Defines pair iteration, squared-distance detection, and midpoint-based separation; defers spatial partitioning.
Examples
Uses enemies with equal radii, compares their separation with their combined radii, and moves overlaps apart from their midpoint.
What you can do after
Build it from scratch by checking enemy pairs, testing squared distance, and separating overlaps in opposite directions.
How it connects
Connects collision detection with squared distance and spatial partitioning.

This explainer was generated by Manning's knowledge graph from the text of High Performance Unity Game Development. The section links point to the parts of the book it draws on.