Switch Cameras when Player is visible?

I have two cameras in my scene and they are side by side…i want the game to switch to whatever camera sees my player at the moment.

What happens when they both see the character? Are they orthographic or perspective cameras?

1 Answer

1

The first thing you need to do is check to see if the player object is within the camera view frustum, then simply edit the depth value of each camera to coincide with what should display.

It’ll go a little something like this;

var posVector = GameObject.Find("Camera 1").camera.WorldToScreenPoint(GameObject.Find("player").transform.position);
var posVector2 = GameObject.Find("Camera 2").camera.WorldToScreenPoint(GameObject.Find("player").transform.position);

if(posVector.x > 0 && posVector.y > 0){
//Player in view frustrum of camera 1
GameObject.Find("Camera 1").camera.depth = -1;
GameObject.Find("Camera 2").camera.depth = 1;
}else if(posVector1.x > 0 && posVector1.y > 0){
//Player in view of camera 2!
GameObject.Find("Camera 1").camera.depth = 1;
GameObject.Find("Camera 2").camera.depth = -1;
}

I assume this is for a scrolling RPG or something along the lines of that ? Perhaps an adventure RPG ?

what if i have lots of cameras?

im getting unknown identifier posvector 1 and 2

You should be using posVector not posvector. It's case sensative. With regards to multiple cameras, simply add a new "var posVector2 = GameObject.Find("Camera 2").camera.WorldToScreenPoint(GameObject.Find("player").transform.position); " with the 2 being the next number in sequence, and then add a new else if line to correspond with the newly added variable.

Hi Everyone, I have created an importable asset which provides you with a single C# script where you put your cameras in the list of cameras, and it will automatically handle your camera switching, no coding, no cost, no worries. Enjoy~ http://koharu.asia/download/SS_Camera_Changer.unitypackage