- Home /
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?
Answer by sarmth · Mar 17, 2013 at 05:30 AM
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 ?
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~