Translation in Godot – Complete Guide

Welcome to our in-depth exploration of the Translation class in Godot 4. As the gaming community grows increasingly global, the ability to bring your game to audiences across different languages becomes paramount. Translation tools in game engines like Godot help developers localize their games, ensuring players around the world can enjoy the gaming experience in their native tongue. In this tutorial, we’ll take a deep dive into how the Translation class can be utilized to map strings and handle pluralization, enhancing your game’s accessibility and broadening its reach.

What is the Translation Class?

The Translation class in Godot 4 is a powerful resource for game developers looking to add internationalization to their games. It allows for the mapping of strings to their individual translations, making it much easier to manage different language versions of your game’s text content.

What is it for?

This class is designed for projects where you need to support multiple languages. It offers an efficient way to organize and retrieve translated strings within your games, handling singular and plural forms, as well as providing context for translations to ensure accuracy and relevancy.

Why Should I Learn It?

Learning to work with the Translation class enables you to make your game accessible to a much wider audience. Understanding its capabilities not only serves to expand your reach but also enhances your skills in game development and localization. Additionally, the experience gained can be applied to other programming and development areas, underscoring the versatility of the knowledge.

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

Setting Up Translations in Godot

To begin using the Translation class in Godot 4, you first need to set up translation resources. A translation resource contains the mappings of original strings in your game to their respective translations in different languages. Here’s how to create a new translation resource:

var translation = Translation.new()
translation.locale = "es"
translation.add_message("Hello, World!", "¡Hola, Mundo!")

In this example, we create a new `Translation` object and set the locale to Spanish (`”es”`). We then add a message to the Translation, mapping the English “Hello, World!” to the Spanish “¡Hola, Mundo!”.

Loading Translations at Runtime

Once your translations are set up, you can load them into the game at runtime to change languages on the fly. This is done by adding them to the ProjectSettings:

ProjectSettings.get_setting("locale/translations").add(translation)

By adding the translation resource to the project settings, you make it available to the entire project. This lets any object within your game access the translations.

Retrieving Translated Strings

After translations are loaded, you retrieve translated strings using the `tr` function. It looks for the string in the current language translations:

var my_string = "Hello, World!"
var translated_string = tr(my_string)
print(translated_string)  # Outputs "¡Hola, Mundo!" if Spanish is set

Here, `tr(my_string)` will look up “Hello, World!” in the current language’s translation mappings and return the translation.

Handling Different Plurals

Handling plurals can be tricky when it comes to localization, as different languages have different rules for pluralization. Godot’s `TranslationServer` handles plurals using `ngettext`:

var singular_msg = "I have found {n} apple."
var plural_msg = "I have found {n} apples."
print(TranslationServer.ngettext(singular_msg, plural_msg, 1))
print(TranslationServer.ngettext(singular_msg, plural_msg, 5))

The `ngettext` function takes in the singular and plural forms of the message, along with a number, and selects the appropriate form. It replaces `{n}` with the number provided.

Using TranslationServer for Localization

The TranslationServer is a centerpoint for managing your game’s localization. You typically interact with it for changing the current language:

TranslationServer.set_locale("es")

Calling `set_locale` with the language code “es” will instruct the TranslationServer to switch the language to Spanish. All subsequent calls to `tr` will then use this locale to look up translations.

Stay tuned, as in the upcoming sections we’ll build upon these concepts with more advanced examples, showcasing how the Translation class can be fully leveraged in your Godot projects to achieve a seamless internationalization process.Now that you’re familiar with the basics, let’s expand on our knowledge by exploring some advanced concepts and examples that involve the Translation class.

Advanced Usage of Translation Resources

Imagine you’re adding multiple languages to your game. Instead of setting up translations one by one, you’d use a `.csv` or similar file to import all translations at once. Godot supports importing translations from such files directly into the engine.

# Assuming you have a CSV file imported with the translations
var spanish_translation = load("res://translations/es_translation.tres")
ProjectSettings.get_setting("locale/translations").add(spanish_translation)

Using `load`, we add the entire translation resource for Spanish, which includes all the strings we have translated in the CSV file.

Dynamically Updating On-Screen Text

For dynamic text that changes depending on user input or game events, you’d use the `tr` function combined with the `format` method.

var name = "Alex"
var greeting_template = tr("Hello, {name}!")
var greeting = greeting_template.format({"name": name})
print(greeting)  # Outputs "Hello, Alex!" assuming that's the proper translation

By using `format`, you can replace placeholders within the translated string effortlessly.

Handling User Interface (UI) Translations

When working with UI elements, such as labels or buttons, you will want the text to update automatically based on the current language.

var label = Label.new()
label.text = tr("Start Game")
add_child(label)
# When the locale is changed, the label will automatically update
# if the scene is reloaded or by running label.text = tr("Start Game") again

Godot’s UI nodes don’t automatically update when the locale changes. To refresh the UI with the correct translations, you can either reload the scene or set the text again as shown above.

Localizing Images and Other Resources

Localization in games is not limited to text. You might also need to localize images, audio files, or other assets for different regions.

# Example of changing an image based on locale
var sprite = Sprite.new()
if TranslationServer.get_locale() == "ja":
    sprite.texture = load("res://images/button_start_ja.png")
else:
    sprite.texture = load("res://images/button_start.png")
add_child(sprite)

This snippet adjusts a sprite’s texture depending on the current locale, allowing for visual localization, like translating the text on a start button.

Binding the update_translations Function

To handle the translation changes in real-time when the locale is switched, you can bind a function to the `locale_changed` signal of the TranslationServer.

func _ready():
    TranslationServer.connect("locale_changed", self, "update_translations")

func update_translations():
    for node in get_tree().get_nodes_in_group("localizable"):
        if node is Label:
            node.text = tr(node.text)
        # Add more cases for other node types if necessary

Any node containing text that needs to be localized can be added to the “localizable” group. When the locale is changed, `update_translations` is called, ensuring all text is updated.

With these examples, you should now have a more comprehensive understanding of the Translation class and related localization mechanisms in Godot 4. By implementing these techniques, you can set your game up for a truly global audience, adapting to various languages and cultural nuances with ease. Whether you’re an indie developer or part of a larger team, mastering Godot’s Translation class is a step towards making games that resonate worldwide.Localization in game development enhances player engagement by providing them with an experience in their native language. The Translation class in Godot 4 eases this process through various functionalities. Here are more practical code examples to help you utilize these features in your game projects.

Switching Languages with UI Interaction

Let’s create a simple way to switch languages through UI interaction. You can set up a function to be called when a UI button is pressed:

func _on_LanguageButton_pressed(language_code):
    TranslationServer.set_locale(language_code)
    update_translations()

Each button in the UI would be connected to this function, passing the respective language code as an argument (e.g., “en” for English, “es” for Spanish). The `update_translations` function would refresh the displayed text.

Inferring Language Preferences

You can infer the player’s preferred language from the OS language settings and set your game’s language accordingly when starting up:

func _ready():
    var os_language = OS.get_locale()
    TranslationServer.set_locale(os_language)
    update_translations()

Here, `OS.get_locale()` returns the language currently set in the operating system, which is then used to set the game’s language. This provides a seamless and considerate initial user experience.

Formatting Numbers and Currency

Localization also involves formatting numbers and currency correctly. Godot 4’s `String` class provides the `num` function, which helps format numerical values into a localized string representation:

var number = 1234.56
var localized_number = "{num}".format({"num": number})
print(localized_number)  # "1,234.56" in US English, "1.234,56" in many European locales

The `num` function will format the number according to the current locale, taking into account differences such as decimal separators.

Localize Dates and Times

Dates and times are another important aspect to localize. To format dates and times relative to the locale, you could use a method like this:

var datetime = OS.get_datetime_from_unix_time(OS.get_unix_time())
var localized_datetime = "{year}-{month}-{day} {hour}:{minute}".format(datetime)
print(localized_datetime)

This code snippet will output the date and time in a manner that is common to the current locale, such as using a 24-hour or 12-hour clock.

Fallback Languages

In some cases, you might want to provide a fallback language if a string is not available in the selected locale. This prevents showing untranslated text:

var fallback_translation = load("res://translations/en_translation.tres")
TranslationServer.add_fallback(fallback_translation)

If a translation for the chosen locale is not found, Godot will attempt to use the translation from the fallback resource.

Remember, localization is not an afterthought but a feature that should be woven into the very fabric of your game design and development. Implementing these advanced translation and localization techniques with the functionality provided by Godot 4’s Translation class ensures that your game will offer a warm welcome to players from around the globe. With each language you add, you’re not just translating words; you’re breaking barriers and building bridges in the universal language of gaming. Whether you’re a seasoned pro or just starting out, we at Zenva believe in empowering you with the knowledge to make your creations as inclusive and enjoyable as possible. Start localizing today and watch your game go global tomorrow!

Continuing Your Game Development Journey

You’ve taken an important step in exploring the power of the Translation class in Godot 4, but your journey in mastering game development doesn’t have to stop here. We invite you to keep building on your newfound knowledge and skills.

If you’re passionate about creating amazing games and want to dive deeper into game development with Godot 4, check out our Godot Game Development Mini-Degree. This comprehensive program offers a range of project-based courses covering everything from 2D and 3D game creation to understanding GDScript and effective game design. You’ll gain hands-on experience by building cross-platform games and learning at your own pace.

For those who wish to explore a broader spectrum of topics within Godot, we have a variety of courses tailored to different aspects of the engine. Visit our Godot courses page to find the perfect fit for your learning path. Whether you’re starting from scratch or looking to specialize, at Zenva, we’re committed to supporting your growth from beginner to game development pro. Embrace the challenge, and let’s create something extraordinary together!

Conclusion

The world of game development is filled with endless possibilities, and mastering tools like the Translation class in Godot 4 opens up new doors for reaching a global audience. Localizing your game is a step towards inclusivity, ensuring players around the world get to experience your creations in a language they understand. This not only amplifies their enjoyment but also extends your game’s reach far beyond its original market.

Now that you’ve gleaned valuable insights into game localization, why stop here? Embark on a rewarding journey to enhance your skills with our Godot Game Development Mini-Degree, where every lesson gets you one step closer to bringing your dream games to life. Connect with fellow game developers, share your multilingual game projects, and continue to shape the future of interactive entertainment with us at Zenva. Your next game could be the one played by millions around the world – in their own language!

FREE COURSES
Python Blog Image

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