DisplayServer in Godot – Complete Guide

When it comes to creating games or interactive applications, the underlying systems that manage the display, window, and events are crucial. In the Godot Engine, a powerful and versatile tool that serves this need is the DisplayServer class. Being able to harness the functionalities provided by DisplayServer can unlock a new level of control and customization for developers, allowing them to create more immersive and responsive gaming experiences. Whether you’re just starting your journey in game development or you’re a seasoned coder, understanding the workings of DisplayServer in Godot 4 will undoubtedly be a beneficial addition to your skillset.

What is DisplayServer?

The DisplayServer class in Godot 4 is an interface that provides a vast array of low-level window management capabilities. It acts as a bridge between your game and the operating system’s display servers, overseeing tasks such as handling the clipboard, managing cursors, processing input events, and controlling window properties.

What is it for?

The functionalities of DisplayServer are instrumental in crafting the presentation layer of a game, dictating how content is rendered and displayed to the user. It offers fine-tuned control over windows (including fullscreen and borderless modes), input management for both keyboard and mouse, and it even extends to features like virtual keyboards for mobile devices.

Why should I learn it?

For game developers, understanding and manipulating the display and window settings is paramount for crafting a seamless user experience. Learning how to use DisplayServer means you’ll have the knowledge to:

– Customize the game window for different platforms and display settings.
– Handle complex input and focus scenarios.
– Integrate with the operating system’s features, like clipboard and virtual keyboard support.

By mastering DisplayServer class functions, you’ll be empowered to create games that look and feel professional, with a level of polish that brings your creative vision fully to life.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Creating and Configuring a Window

To start working with the DisplayServer, the first step is to create and configure a window for our game. Let’s begin by setting up a window with specific dimensions and a title.

var display_server = DisplayServer.get_singleton()
display_server.window_create()
display_server.window_set_size(1024, 768)
display_server.window_set_title("My Awesome Game")

Once the window is created, you can toggle fullscreen mode or make the window borderless. This is essential for providing different window modes based on user preferences.

display_server.window_set_mode(DisplayServer.WINDOW_MODE_FULLSCREEN)
# To revert back to windowed mode
display_server.window_set_mode(DisplayServer.WINDOW_MODE_WINDOWED)
# To create a borderless window
display_server.window_set_mode(DisplayServer.WINDOW_MODE_BORDERLESS)

Handling Input Events

The DisplayServer is also responsible for processing input events. You can access the current mouse position or check if certain keys are being pressed.

# Get current mouse position
var mouse_position = display_server.window_get_mouse_position()

# Check if the 'W' key is pressed
var key_code = GlobalConstants.KEY_W
var is_w_pressed = display_server.key_is_pressed(key_code)

You can craft more complex input handling functions by connecting to signals that the DisplayServer emits, such as when a key is pressed or when the mouse moves.

display_server.connect("window_key_input_event", self, "_on_key_input_event")
display_server.connect("window_mouse_input_event", self, "_on_mouse_input_event")

func _on_key_input_event(event):
    if event.pressed and event.scancode == GlobalConstants.KEY_ESC:
        get_tree().quit()

func _on_mouse_input_event(event):
    if event.button_mask & MouseButton.LEFT:
        # Handle left mouse button click

Manipulating the Clipboard

Sometimes you’ll need to copy text to or paste text from the system clipboard for in-game purposes. You can do so by using the following methods:

# Copying text to clipboard
display_server.clipboard_set("Text to copy")

# Pasting text from clipboard
var clipboard_text = display_server.clipboard_get()

The ability to interact with the clipboard can come in handy for sharing generated content or easing user input, especially for text-heavy games.

Working with Cursors

Customizing the mouse cursor can greatly impact the aesthetic and usability of your game. The following code snippets show how to change the cursor shape, set a custom image for it, or hide it entirely.

# Set cursor shape to 'IBeam' (useful for text editing scenarios)
display_server.cursor_set_shape(DisplayServer.CURSOR_IBEAM)

# Hide the cursor (ideal for first-person games)
display_server.cursor_set_visible(false)

# To set a custom cursor image
var cursor_image = preload("res://path_to_cursor_image.png")
display_server.cursor_define_image(DisplayServer.CURSOR_ARROW, cursor_image, Vector2())

Custom cursors can be used to better match the theme of your game and also to provide visual feedback to the player, enhancing the overall gaming experience.

Monitoring Window Events

Monitoring and responding to window events is vital in creating an adaptable and user-friendly game. For example, we might want to pause the game when the window loses focus or resize elements when the window size changes.

display_server.connect("window_focus_in", self, "_on_window_focus_in")
display_server.connect("window_focus_out", self, "_on_window_focus_out")
display_server.connect("window_size_changed", self, "_on_window_size_changed")

func _on_window_focus_in():
    # Code to unpause the game

func _on_window_focus_out():
    # Code to pause the game

func _on_window_size_changed():
    # Code to handle resizing UI elements

Managing Multiple Windows

While most games will only require a single window, the DisplayServer can handle multiple windows, which may be useful for auxiliary tools or multi-window applications.

var secondary_window_id = display_server.window_create()

# Move the secondary window to a specific position
display_server.window_set_position(secondary_window_id, Vector2(400, 300))

# Resize the secondary window
display_server.window_set_size(secondary_window_id, Vector2(800, 600))

This can be used to create an integrated development environment (IDE) within the game, or a game that benefits from auxiliary windows displaying different types of content.

Configuring Viewports

The DisplayServer also involves configuring viewports. A viewport is where your game is drawn, and you can manipulate properties like rendering scales and usage of high dynamic range (HDR).

var viewport_id = display_server.viewport_create()
display_server.viewport_set_size(viewport_id, 1280, 720)
display_server.viewport_set_hdr(viewport_id, true)

This is especially important for games aiming to support a variety of display settings, ensuring that visuals are rendered in the best possible quality for players with HDR-enabled screens.

Controlling Display and Window Properties

Further tune the behavior and presentation of displays and windows for your game. Set minimum and maximum sizes, toggle ‘always on top’ behavior, or even change the screen used by a particular window.

display_server.window_set_min_size(Vector2(800, 600))
display_server.window_set_max_size(Vector2(1920, 1080))

# Make the window always on top
display_server.window_set_always_on_top(true)

# Change which screen (monitor) the game window is on
display_server.window_set_current_screen(1)

These features allow developers to ensure that their game runs optimally across different environments and meets specific gameplay or design requirements.

By diving into these examples of what the DisplayServer class can do within the Godot Engine, we see how it serves as the cornerstone for managing display and window properties, handling input, and interacting with the system. Utilizing DisplayServer provides a solid foundation for developing professional, robust, and responsive games or applications. As we continue to explore the Godot Engine and its evolving ecosystem, mastering elements like DisplayServer positions us at the forefront of game development technology.Continuing with the DisplayServer in the Godot Engine opens a pathway for advanced window and event management. These additional functionalities can greatly contribute to a high-quality user experience.

Setting Up a Custom Icon

For game branding, setting a custom icon for the game window is straightforward. Here’s how to change the default icon to a custom image:

var icon = preload("res://icon.png")
display_server.window_set_icon(icon)

A custom icon immediately distinguishes your game in the taskbar or window switcher, adding an extra layer of polish.

Handling Display Scaling

For games that need to adapt to various screen resolutions and densities, you may choose to enable or disable high-DPI mode. In conjunction with viewport scaling, this can ensure your game looks sharp on all displays.

display_server.window_set_use_hidpi(true)

Enable high-DPI mode to maintain the visual quality on retina or 4K displays, where pixels are denser.

Controlling Screen Orientation on Mobile

When developing for mobile, controlling the orientation of the screen is essential. DisplayServer allows for this control programmatically:

display_server.screen_set_orientation(DisplayServer.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)

This snippet would set the mobile game to adjust its orientation based on the device’s sensors, but only allowing landscape modes.

Managing Screen Sleep and Battery

Keeping the screen awake might be necessary for specific types of games or applications. To prevent the screen from going to sleep:

display_server.screen_set_keep_awake(true)

This setting is particularly important for applications where user interaction is infrequent but continuous display is necessary.

Working with Multiple Monitors

You may want your game or tool to identify and interact with multiple monitors. DisplayServer helps with obtaining the number of screens and their respective properties:

var screen_count = display_server.get_screen_count()

# Retrieve information such as the DPI or screen position
for i in range(screen_count):
    var dpi = display_server.screen_get_dpi(i)
    var position = display_server.screen_get_position(i)

Knowing the screens’ properties allows for customized behaviors and layouts optimized for multi-monitor setups.

Custom Stretching Policies

For games that scale to different aspect ratios, setting up a custom stretching policy around the viewports is beneficial.

display_server.window_set_stretch(
    DisplayServer.STRETCH_ASPECT_KEEP_HEIGHT, 
    DisplayServer.STRETCH_MODE_2D, 
    1920, 1080
)

This can ensure that your game maintains its aspect ratio without distortion, scaling assets as necessary.

Interfacing With the Native Platform

Lastly, DisplayServer provides some level of access to native platform functionalities. For example, you can access information about the native window handle which is useful for certain integrations:

var native_handle = display_server.window_get_native_handle()
# Use native_handle for platform-specific functionality

With this functionality, you could create plugins or extend your application in ways that require direct interaction with the underlying operating system.

As we’ve explored, Godot’s DisplayServer offers granular control not only over basic window management but also over system interactions, allowing for a deeply tailored user experience, whether you’re developing for desktop, mobile, or multi-screen environments. Embracing these capabilities is key to delivering top-tier games and applications, and we at Zenva are excited to help pave the way for aspiring developers and seasoned professionals alike to make the most out of tools like the Godot Engine.

Continuing Your Game Development Journey

Embarking on the journey of game development is an exhilarating experience, full of creative and technical growth. If you’ve enjoyed exploring the intricacies of the DisplayServer class in Godot 4 and are eager to delve deeper, your path to mastery in game creation is just beginning. With the Godot Game Development Mini-Degree, you can step confidently into the expansive world of game development with our comprehensive set of courses. Discover how to build cross-platform games and learn through project-based lessons on a wide array of essential topics.

Our Mini-Degree is the perfect next step for those who are determined to consolidate their skills and expand their knowledge in Godot 4, covering areas from 2D and 3D game creation to user interface design and complex game mechanics. And for those who are looking to widen their perspective even further, explore our broader selection of Godot courses, tailored to cater to developers of all levels, from beginner to professional.

Take advantage of project-based learning, quizzes, and the flexibility of tailoring your education to your schedule. Let Zenva be your guide on this exciting journey, turning your passion for games into a tangible skill set that can animate worlds, captivate audiences, and bring your vision to life.

Conclusion

As your guide through the enthralling realm of game development, we at Zenva understand the value of a solid foundation and continuous learning. Clearly, the DisplayServer in Godot 4 is a tool of immense power for those looking to perfect their game’s presentation and interaction with various systems. By embracing this knowledge, you stand on the brink of transforming your creative ideas into engaging experiences for gamers around the globe.

Remember, this is but a glimpse into the potential that awaits within Godot 4 and game development as a whole. We invite you to join us in the Godot Game Development Mini-Degree to further demystify game development, and gain the skills that will anchor your place in the industry. Whether you’re crafting games for fun or aspiring to build the next big title, this journey with Zenva is one step forward in bringing your dream games to reality. Embark on this journey today and unlock the full potential of game development.

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.