Enable/Disable Split screen with GDScript

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Skydome

I am trying to make it so that if player 2 goes out of screen the screen splits. I can detect with visibility Notifier when P2 goes out but having splitting the screen. It’s not working properly. This is my scene for the split screen.

Main (Node2D)
- Viewports (HBox Container)
  - ViewportContainer1 (Viewport container)
   - viewport1 (viewport)
     -World(Scene with the players, NPCs, tilemap etc.)
     - Camera2D
  - ViewportContainer2 (Viewport container)
   - viewport2 (viewport) For Player 2
     - Camera2D

And I am experimenting with various code for the split screen. The split screen works fine when I set it up from the editor with the script it’s off.

Sometimes the split screen works fine but the regular screen is the issue. Sometimes the screen splits but the second screen remains broken. Sometimes the screen remains split. Sometimes instead of splitting the second viewport just takes up half of the screen on top of the first. I’m trying out various things but something is just always off.

I am using these methods.

func Enable_Split_Screen():
	#ViewPortContainer2.size_flags_horizontal =2 //Not working
	ViewPortContainer2.rect_position = Vector2(640,0)
	ViewPortContainer2.rect_size = Vector2(639,720)
	ViewPortContainer1.rect_size = Vector2(639,720)
	viewport2.size = ViewPortContainer2.rect_size
	viewport1.size= ViewPortContainer1.rect_size

func Disable_Split_Screen():
	#ViewPortContainer2.size_flags_horizontal =1
	ViewPortContainer2.rect_position = Vector2(1280,0)
	ViewPortContainer2.rect_size = Vector2(0,720)
	ViewPortContainer1.rect_size = Vector2(1280,720)
	#viewport2.size = ViewPortContainer2.rect_size
	#viewport1.size = ViewPortContainer1.rect_size

Appreciate any insight regarding this.

:bust_in_silhouette: Reply From: Skydome

ViewPortContainer2.size_flags_horizontal =3 for enable

ViewPortContainer2.size_flags_horizontal =1 for disable

This seems to be working. This was quite confusing . Not a lot of information on this.

:bust_in_silhouette: Reply From: zenbobilly

The HBoxContainer does all the sizing of the child viewport controls, so you can’t change their size (rect), anchor or margin values directly. You must change the “ratio” that each of the child controls occupies on the parent (in your case, the Viewports node (HBox Container)). Controls are designed to be dynamically sized so that you don’t ever really specify exact sizes for child controls in this regard. Attempting to do so will either be ignored or result in strange glitches that you are talking about.