Thursday, September 5, 2013

Unity Helper Methods #2: BoxCollider.GetPointInCollider

/// <summary>
/// Returns a random world point inside the given BoxCollider
/// </summary>
public static Vector3 GetPointInCollider(this BoxCollider area)
{
    var bounds = area.bounds;
    var center = bounds.center;

    var x = UnityEngine.Random.Range(center.x - bounds.extents.x, center.x + bounds.extents.x);
    var z = UnityEngine.Random.Range(center.z - bounds.extents.z, center.z + bounds.extents.z);

    return new Vector3(x, 0, z);
}

I normally use this method to get a random spawnpoint within my spawn area represented with a BoxCollider (set to a trigger of course).

Notice how I hardcode Y to 0 because the Y position is irrelevant to me since that is set by code outside of this method.

public BoxCollider spawnArea;

void SpawnWhatever() 
{
    Vector3 spawnPoint = spawnArea.GetPointInCollider();
    // Spawn something at the random spawnpoint we got
    // ...
}