Split-screen in Godot 3D with a single Scene containing 2 cameras

402 views Asked by At

I am new to Godot, transitioning from Unity and I still do not have a good grasp on how scenes and viewports interact. I am making a game with two players: one pilots an aircraft and the other shoots a turret on top of it. Each player has a different camera, so I want the game to be split-screen. Most tutorials for Godot 3D implement split-screens like this:

Spatial
    Viewport1
        Player1
           Camera1
    Viewport2
        Player2
           Camera2

However, that solution does not work for me because it separates the cameras, and I would like to have both cameras together in a single scene like this:

Player
    Body
        Camera1
    Turret
        Camera2

I tried this:

Control
    GridContainer
        Player

With the player already having 2 cameras as described previously, but only 1 camera gets displayed. Is there any good way to implement this? Alternatively, I could make the body and the turret separate scenes and make them follow each other with code, but getting them together in a single scene simplifies other problems.

2

There are 2 answers

0
Theraot On BEST ANSWER

Sadly the setters for the Camera(3D) in Viewport are not exposed to scripting (this is because we are supposed to use the current property on the Camera(3D)).

But we can do the change at a lower level by calling viewport_attach_camera on the RenderingServer (in Godot 4) or VisualServer (in Godot 3) to change the current Camera(3D) of the Viewport to an arbitrary one with .

The method wants the RID (Resource ID) of the Viewport (which you get by calling get_viewport_rid on it) and of the Camera(3D) (which you can get by calling get_camera_rid() on it).

This also means that the code that does this setup must be able to reference both the Viewport and its intended Camera(3D).

0
user2635469 On

Thanks for Theraot for answering the question! So the final implementation looked like this:

Main
   Player
   GridContainer
       SubViewportContainer
            SubViewport
       SubViewportContainer
            SubViewport

The player had 2 cameras, like so:

Player
    Camera3D
    Turret
        Camera3D2

And I added this script to the GridContainer, which sets up the split-screen:

extends GridContainer


@onready var viewport1: SubViewport = $SubViewportContainer/SubViewport
@onready var viewport2: SubViewport = $SubViewportContainer2/SubViewport
@onready var Camera1: Camera3D = get_node("../Player/Camera3D")
@onready var Camera2: Camera3D = get_node("../Player/Turret/Camera3D2")


func _ready():
    var Camera_rid1 = Camera1.get_camera_rid()
    var Camera_rid2 = Camera1.get_camera_rid()
    var viewport_rid1 = viewport1.get_viewport_rid()
    var viewport_rid2 = viewport2.get_viewport_rid()
    RenderingServer.viewport_attach_camera(viewport_rid1, Camera_rid1)
    RenderingServer.viewport_attach_camera(viewport_rid2, Camera_rid2)