TranslationServer in Godot – Complete Guide

Welcome to this deep-dive into the TranslationServer class in Godot 4. As game developers, creating experiences that reach as wide an audience as possible is one of our main goals. One path to achieving this is through localizing our games into multiple languages, ensuring that players from different regions can enjoy our work in their native tongue. Godot, being an incredibly versatile and developer-friendly engine, offers a powerful tool to help in this process: the TranslationServer. With the aid of this server, you can manage languages and translations with ease, enabling you to globalize your game with simplicity and efficiency.

What Is The TranslationServer?

The TranslationServer is a core class in the Godot engine that takes charge of language translations within a project. It’s the backbone of the engine’s localization system, handling various translations and making it possible to switch between different languages during runtime. This is essential for developers who aim to publish their games in different regions and cater to a global audience.

What Is It For?

Godot’s TranslationServer primarily helps manage different translations. With it, you can add, remove, and update translations without a hassle. Moreover, it allows you to query available languages and countries, standardize locale formats, and even utilize pseudolocalization for testing. The server aims to make translations seamless and straightforward so that developers can focus on creating immersive multilingual experiences.

Why Should I Learn It?

Understanding the TranslationServer can significantly expand your game’s reach by making it accessible to a non-English speaking audience or speakers of multiple languages. By learning how to use this feature, you help ensure that the player’s first impression of your game isn’t hindered by language barriers. Moreover, having this skill allows you to work on a broader range of projects globally and equips you with the knowledge to engage in the growing conversation around game localization.

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

Setting Up Translation Files

Before we dive into the code, let’s ensure that we have our translation files ready. In Godot, translations are typically stored in CSV or PO files. For this tutorial, we’ll use a simple CSV file that might look like this:

"KEY","en","es"
"GREETING","Hello, World!","¡Hola, mundo!"
"FAREWELL","Goodbye!","¡Adiós!"

Once you’ve prepared your translation files, you need to tell Godot about them and load them into the TranslationServer. Here’s how you would set this up programmatically on your game’s start-up:

var translation = Translation.new()
translation.load("res://translations.csv")
TranslationServer.add_translation(translation)

It’s crucial to perform this step at the beginning of your game to ensure that all the translations are available when players start interacting with your game.

Switching Languages

Now that we have our translations loaded, switching languages is a matter of changing the current locale. Let’s see how to do it:

func _change_language(new_locale):
    TranslationServer.set_locale(new_locale)

You might call this function with a parameter like “es” for Spanish when a player selects their preferred language from the game’s options menu.

Querying Available Languages

It’s also possible to get a list of all the languages your game supports. You may want to display these to players in a settings menu, for example. Here’s how to get that list:

var supported_languages = TranslationServer.get_loaded_locales()
for locale in supported_languages:
    print("Supported Locale: ", locale)

This loop will print out each language code that has been loaded into the server.

Updating Translations Dynamically

Occasionally, you might find the need to add or remove translations dynamically during runtime. For instance, when downloading additional language packs or when receiving updates. Here’s how you would handle such cases:

Adding a new translation:

var new_translation = Translation.new()
new_translation.load("res://new_translation.csv")
TranslationServer.add_translation(new_translation)

Removing a translation is as simple as:

TranslationServer.remove_translation(new_translation)

Remember to refresh the UI or relevant text display mechanisms to ensure that your changes take effect immediately.

Using Translation Keys in Code

To use our translations within the game’s code, we can reference the keys we set up in our CSV file. Godot’s `tr()` function looks up translation keys and returns the corresponding text for the current locale.

Let’s apply the greeting from our translation file to a Label node:

func _ready():
    $Label.text = tr("GREETING")

When you run the game, you’ll see “Hello, World!” on the screen, or “¡Hola, mundo!” if you’ve set the locale to Spanish.

In the next part of this tutorial, we will continue with more advanced uses of the TranslationServer and delve into pseudolocalization, which is crucial for testing your localization efforts. Stay tuned for further insights into making your game as globally friendly as possible!

Advanced Localization with TranslationServer

Localizing UI elements is just the tip of the iceberg when it comes to the capabilities of the TranslationServer. Let’s look at some advanced techniques and code examples to help you make the most out of Godot’s powerful localization system.

Pseudolocalization for Testing

Pseudolocalization is a localization testing method used to ensure that a game will be ready for translation into other languages. It involves replacing characters in strings with accented versions or other symbols to mimic the effect of translation, often resulting in longer strings. This helps identify potential issues with text display in your game’s UI. Here’s an example of implementing pseudolocalization:

func _pseudolocalize(text):
    var pseudo_text = ""
    for char in text:
        pseudo_text += char + "̃"  # Adds a tilde over each character
    return pseudo_text

func _ready():
    $Label.text = _pseudolocalize(tr("GREETING"))

Using this method during development can highlight issues like overlapping text, cutoff strings, and layout problems that may occur with translations that have different lengths from your base language.

Formatting Strings with Placeholders

Sometimes you’ll have dynamic content within your translations, such as player names or item counts. For these, use placeholders in your translation keys that can be replaced at runtime:

Here is an example of a translation CSV with placeholders:

"KEY","en"
"COINS_LEFT","You have {coins} coins left."

Next, we populate it using the `tr()` function and the `format()` method in GDScript:

func _ready():
    var remaining_coins = 5
    $Label.text = tr("COINS_LEFT").format({"coins": remaining_coins})

This will result in the Label displaying “You have 5 coins left.” to the player.

Handling Plural Forms

Different languages have different rules for pluralizing words, which can be a challenge when localizing your game. Godot’s TranslationServer doesn’t handle plural forms natively, but you can set up a system using singular and plural keys:

CSV example with singular and plural keys:

"KEY","en"
"COIN_SINGLE","You have one coin left."
"COIN_PLURAL","You have {coins} coins left."

And the code to use these keys could look like:

func _get_coin_text(coin_count):
    if coin_count == 1:
        return tr("COIN_SINGLE")
    else:
        return tr("COIN_PLURAL").format({"coins": coin_count})

func _ready():
    var coins = 3
    $Label.text = _get_coin_text(coins)

For more elaborate pluralization support, consider using an external i18n library or creating a more complex pluralization function tailored to your needs.

Changing Fonts for Different Languages

Some languages may require different fonts to appropriately display characters, such as Asian languages with unique character sets or languages like Arabic that use a right-to-left script. For these cases, you can dynamically change the fonts based on the selected locale:

func _set_font_for_locale(locale):
    var font_resource = "res://fonts/font_for_" + locale + ".ttf"
    var font = load(font_resource)
    $Label.font = font

func _ready():
    _set_font_for_locale(TranslationServer.get_locale())

Remember to prepare fonts that support necessary characters for all languages you plan to include in your game.

Each of these examples demonstrates how to gain more control over the localization process in your games. While the translation and support for multi-language content can be complex, with the Godot TranslationServer, you have a robust starting point. Localizing your game not only helps it reach a wider audience but also shows respect for different cultures by making your game more accessible to them. Happy coding and happy translating!Certainly! As we delve deeper into localization with Godot’s TranslationServer, it’s crucial to remember the importance of context for translations, which can influence the meaning of words or phrases. Additionally, it’s worth exploring how you can fine-tune the usability of your game for various locales, such as adjusting date formats or currency symbols.

Providing Context for Translators

When working with translators, it’s essential to provide context for each string to ensure accurate translations. While this isn’t directly a code example, you can structure your CSV files to include an additional “context” column that might not be used by your game, but can be very helpful for translators.

"KEY","en","es","Context"
"ITEM_FISH","Fish","Pescado","noun - an item in the inventory"
"VERB_FISH","Fish","Pescar","verb - the action of fishing"

In your code, you ignore the context column but it provides necessary information for someone translating without intimate knowledge of the game.

Localizing Date Formats

Date formats vary across locales, which can be quite confusing for players if not localized properly. While Godot does not have built-in functions specifically for formatting dates, you can set up a system for this within your game:

CSV example for date formats:

"KEY","en","es"
"DATE_FORMAT","MM/DD/YYYY","DD/MM/YYYY"

In GDScript, you can configure the date format like so:

func _localize_date(date):
    var format_string = tr("DATE_FORMAT")
    return date.strftime(format_string)

func _ready():
    var date = OS.get_date()
    $Label.text = _localize_date(date)

This example assumes you have a date object with a `strftime` method, which would need to be implemented in GDScript.

Localizing Numbers and Currency

Another aspect that varies from locale to locale is number formatting. Here is an example of how you might handle number localizations, particularly for currency, by replacing dots with commas for thousands separators or adapting the currency symbol:

CSV example for currencies:

"KEY","en","es"
"PRICE","Price: $","Precio: €"

You might then have a localization function like this:

func _localize_price(value):
    var localized_price = tr("PRICE") + str(value).replace(".", ",")
    return localized_price

func _ready():
    var price = 1999.99
    $Label.text = _localize_price(price)

Right-to-Left Text Support

For languages that read right-to-left, such as Hebrew or Arabic, you’ll need to adjust the UI to ensure proper readability. Godot doesn’t currently offer right-to-left text support out of the box, but you can add it yourself with some custom adjustments:

func _adjust_for_rtl(text):
    # This is a placeholder for your RTL conversion logic
    var rtl_text = some_rtl_conversion_function(text)
    return rtl_text

func _ready():
    if TranslationServer.get_locale() == "ar":
        $Label.text = _adjust_for_rtl(tr("GREETING"))

This simplistic example assumes you’d include an external function (or set of functions) necessary to process text for right-to-left languages, as `some_rtl_conversion_function` indicates.

Testing Localization In-Game

Finally, when testing your game’s localization, it can be useful to create a debug menu to change languages on the fly. This enables you and your testers to easily switch locales without having to restart the game:

func _on_LanguageButton_pressed(button):
    var locale = button.get_text()  # Assuming the button's text is the locale code
    TranslationServer.set_locale(locale)
    _refresh_ui_text()  # A function to update all UI text

# Connect this to your language selection buttons in the editor or with code

Localization requires ongoing attention and maintenance. Code snippets like these not only make your initial localization setup more robust but also make it easier to update and add new languages as your game evolves.

Remember to test thoroughly and consider cultural nuances that may affect the way players interact with your game. As you continue to improve your localization efforts, you strengthen the global accessibility of your game, inviting players around the world to enjoy the immersive experiences you create.

Continuing Your Godot Localization Journey

You’ve now made fantastic progress in understanding the crucial aspects of localization within Godot 4, and we hope it has sparked your curiosity and passion for game development even further. Localizing your game is a powerful step towards sharing your creation with the world, and it’s just the beginning of crafting an engaging global experience.

To keep expanding your skillset, we invite you to explore our Godot Game Development Mini-Degree. It is a treasure trove of knowledge for those eager to dive into game building, covering a range of essential topics that will enhance your capabilities as a developer. Your journey from beginner to professional is supported by our wealth of courses, each designed to walk you through the many facets of game creation, building a robust foundation for your career in game development.

And for those who seek an even broader spectrum of Godot courses, Zenva has you covered. Visit our full collection of Godot courses, catering to diverse learning needs and interests. With Zenva, you can learn at your own pace, anytime, anywhere, and on any device. Start crafting your future in game development today!

Conclusion

Delving into Godot’s TranslationServer is an adventure that unlocks a new realm of possibilities for your games. By harnessing the power of localization, you have taken a significant step towards making your gaming experiences truly universal. Whether you’re just starting out or you’re a seasoned developer refining your skills, remember that the journey of learning and growth is continuous and ever-rewarding.

At Zenva, we’re proud to be your companions on this journey. The doors to our Godot Game Development Mini-Degree are always open, offering a path paved with expertise and knowledge that leads to your success in game development. Keep exploring, keep learning, and let’s build games that resonate across the globe, together!

FREE COURSES
Python Blog Image

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