switch between multiple cameras based on distance to target

Hi,

I'd like to have multiple cameras placed around a map and have the cameras switch automatically depending on which is closest to the player so that they follow the players movements no matter where he goes.

I've attached a basic LookAt script to the cameras, but the problem is the switching. How would I determine which camera is closest to the player and enable it, then disable all others.

I figured that putting the cameras in an array (somewhat like waypoints) might work, but I'm having trouble figuring out how to determine which of the cameras in the array is closest to the player. I understand Vector3.Distance. The problem is, how do I iterate through the array and pick the one with the shortest distance? Thanks for the help.

You have the right idea with putting the cameras in an array and iterating over them. As for the problem of finding the camera closest to the player, here's some pseudocode (untested):

// Find the closest point in an array of points to a query point 'p':
float minDistance = float.MaxValue;
int closest;
for (int i = 0; i < points.Length; ++i) {
    float distance = Vector3.Distance(p, points*);*
 *if (distance < minDistance) {*
 *minDistance = distance;*
 *closest = i;*
 *}*
*}*
*// 'closest' is now the index of the closest point to 'p'.*
*```*
*<p>Adapting this to find the camera closest to the player should be straightforward. (Note that this can be optimized slightly by comparing squared distances rather than distances. However, any difference in performance is unlikely to be noticeable in this context.)</p>*

Thanks, Jesse. You're posts are always very helpful. It will take me a couple of days to adapt this to my purposes. Once I do, I'll post it here for others to use. You're the best.

Here's the code based on your example. It's in Javascript.

var multicam : Camera[];
static var myrocket: GameObject;
myrocket = GameObject.FindWithTag ("rocket");

function Update () 
{
var minDistance: float = 5000;
var closest: int;

for (i = 0; i < multicam.Length; i++) 
{
var distance = Vector3.Distance(myrocket.transform.position, multicam*.transform.position);*
 *if (distance < minDistance)* 
 *{*
 *minDistance = distance;*
 *closest = i;*
 *Debug.Log(closest);*
 *}*
 *for (cameras in multicam)*
 *{*
 *if (cameras !=multicam [closest])*
 *{*
 *cameras.enabled = false;*
 *cameras.GetComponent(AudioListener).enabled = false;*
 *}*
*}*
*multicam[closest].enabled = true;*
*multicam[closest].GetComponent(AudioListener).enabled = true;*
*}*
*}*
*```*