8 - Active Camera

Create 3 cameras in the current scene, and now we'll move to the codeing part.
Import the game engine module, define the current python controller and the owner object if necessary.
Our scene shows us the current active camera, so let's define our current scene and get active camera like so. Oh also put it in a function if necessary.

try:
    import Range
except:
    import bge as Range
    
cont = Range.logic.getCurrentController()
own = cont.owner
scene = Range.logic.getCurrentScene()

def main():
    print(scene.active_camera)

For now we print to know what our active camera is.
If you've tried to run the game without looking thru a camera and just run the game in normal viewport your console would be printing __default__cam__.

Now we have 3 cameras in the scene and we don't want to look through the normal viewport. So we check if our camera is in the default viewport and if so, we will randomly look through one of our 3 cameras which we've added previously.

try:
    import Range
except:
    import bge as Range

import random

cont = Range.logic.getCurrentController()
own = cont.owner
scene = Range.logic.getCurrentScene()

def main():
    if scene.active_camera.name == "__default__cam__":
        scene.active_camera = random.choice(scene.cameras)
    else:pass
    

Here after the main() we check if our camera is __default__cam__ and if so we randomly choose a camera from the list scene.cameras.
The reason why we used name attribute after scene.active_camera is, when you compare them without that name attribute you are comparing your object with a string. This is not a vaild condition and hence it will not be satisfied.

Download the project file