OptimizedTranslation in Godot – Complete Guide

When it comes to creating games or applications, one key aspect is ensuring that they can reach a broad audience by supporting multiple languages. This is where Godot’s OptimizedTranslation class shines. In Godot 4, an engine celebrated for its versatility and ease of use, we find an incredible resource for localizing our projects efficiently. Delve into this tutorial to discover how this powerful class can streamline your translation workflow and reduce memory footprint with real-time compressed translations.

What Is OptimizedTranslation?

OptimizedTranslation is a class in Godot 4 that inherits from the Translation class—providing a means to store translations in a way that is efficient in terms of space. It’s specifically designed for CSV Translations and is used by default when working with this format in Godot.

What Is It For?

This class is utilized to hold translations that have been compressed in real-time to create incredibly small dictionaries. This both optimizes the game’s performance and reduces the game’s overall storage requirements.

Why Should I Learn It?

Learning how to use the OptimizedTranslation class empowers you to:

– Deliver your game with multiple language support efficiently.
– Understand deeper Godot resource management and localization features.
– Keep your game’s memory footprint low, allowing it to run better on various devices.

It is essential for game developers who aim to reach an international audience while maintaining their game’s performance.

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

Creating and Using CSV Translations

Before delving into OptimizedTranslation, it’s fundamental to understand how to create and use CSV translations in Godot. The CSV (Comma-Separated Values) file will hold all your text data, organized by keys and languages.

"KEY", "ENGLISH", "SPANISH", "FRENCH"
"GREET", "Hello", "Hola", "Bonjour"
"FAREWELL", "Goodbye", "Adiós", "Au revoir"

To implement the CSV file in Godot, first, you need to import it as a translation:

var translation = Translation.new()
translation.set_locale("en")  // sets the locale to English
translation.load_from_csv("res://translations.csv") // load the CSV file
ProjectSettings.get_singleton().add_translation(translation)

Initializing OptimizedTranslation

Once you have your CSV translations in place, you can optimize them. For this, Godot’s OptimizedTranslation class is used.

var optimized_translation = OptimizedTranslation.new()
optimized_translation.set_locale("en")  // set the locale as you did before
optimized_translation.load_from_csv("res://translations.csv") // load CSV
ProjectSettings.get_singleton().add_translation(optimized_translation)

Here, the translation is loaded from CSV as before, but using an OptimizedTranslation object instead of the base Translation class. This will enable the real-time compression.

Accessing the Translations in GDScript

With translations loaded, you can access them in your GDScript using the tr function, which looks up translation keys based on the current locale.

var greeting_text = tr("GREET")  // Returns "Hello" for English locale
var farewell_text = tr("FAREWELL")  // Returns "Goodbye" for English locale

This GDScript code will access the “GREET” and “FAREWELL” keys, providing their values based on the currently set locale.

Changing Locales at Runtime

A game may need to switch languages based on player preference. To change the locale at runtime and thus change the language of your game, you can use the following code:

func _on_LanguageButton_pressed(new_locale):
    ProjectSettings.set("locale/translation_remaps", {})
    OS.set_locale(new_locale)  // e.g., "es" for Spanish
    TranslationServer.set_locale(new_locale)  // notify the translation server

This code provides a possible implementation of a language selection feature. When a language button is pressed, the game’s locale is changed to the corresponding language code such as “es” for Spanish.

Remember, to successfully apply the changes, all text elements that display translated text will need to be refreshed for the new translations to appear.

As we get our translations set up and optimized using the code examples above, we take a pivotal step towards creating truly global games with performances that remain headed towards the upper echelons. Join us in the next part where we’ll explore more advanced uses of the OptimizedTranslation class, such as exporting to other platforms and streamlining the workflow even further. Stay tuned and keep coding!Let’s further enhance our mastery of Godot’s linguistic capabilities by exploring advanced techniques and code examples that utilize the OptimizedTranslation class. Whether it’s iterating through available languages, dynamically updating UI, or handling plurals and genders, these snippets will deepen your understanding and control over your game’s international flair.

Iterating Over Supported Languages

There might be instances where you need to generate a list of all supported languages in your game. The following snippet demonstrates how to iterate over all the loaded translations and retrieve their locales.

var supported_languages = []
for t in ProjectSettings.get_singleton().get_loaded_translations():
    supported_languages.append(t.get_locale())

# Use 'supported_languages' for populating your language selection menu.

Dynamically Updating In-Game Text

When the language is changed, all UI elements displaying text must update to reflect the new translations. To facilitate this, create a signal in a master scene or singleton to notify other nodes when the language changes.

signal language_changed

func _on_LanguageButton_pressed(new_locale):
    # ... (rest of the language change code)
    emit_signal("language_changed")

Then, any text element can connect to this signal and update accordingly.

func _ready():
    # Assuming the signal is in a singleton called 'Global'
    Global.connect("language_changed", self, "_on_language_changed")

func _on_language_changed():
    $Label.text = tr("GREET")

Handling Plurals and Genders

Supporting plurals and genders in translations can be a complex task. You can handle these cases by including logic in your code and extending the translation CSVs. Here’s a simple example that demonstrates handling plurals:

"KEY", "ENGLISH_SINGULAR", "ENGLISH_PLURAL"
"APPLE_COUNT", "There is one apple", "There are %d apples"

func update_apple_count(count):
    var key = "APPLE_COUNT"
    var text = ""
    if count == 1:
        text = tr(key + "_SINGULAR")
    else:
        text = tr(key + "_PLURAL").format([count])

    $AppleCountLabel.text = text

Extracting and Using Parameters in Translations

At times, your translations will need to include dynamic data, like player names or scores. These can be integrated using placeholders in the CSV translation files, which can then be replaced at runtime.

"KEY", "ENGLISH", "SPANISH"
"WELCOME_PLAYER", "Welcome, %s!", "¡Bienvenido, %s!"

func welcome_player(name):
    var welcome_text = tr("WELCOME_PLAYER").format([name])
    $WelcomeLabel.text = welcome_text

Honing your skills with Godot’s translation system allows you to design a seamless localisation experience, transcending the limitations of language for your end users. With these advanced strategies under your belt, you are well-equipped to grasp the intricacies of delivering accessible, inclusive, and internationally adaptable gaming experiences.

Take the next step in crafting your multilingual masterpiece by implementing these insights into your Godot projects. Continue your learning journey as you implement, iterate, and innovate—progressing your game development prowess into newer and broader horizons. We at Zenva are excited to see the worlds you’ll build and the communities you’ll unite with your new, polished linguistic toolkit. Keep coding, and until next time, happy game developing!While we’ve covered quite a bit on using Godot’s localization system, there are always further depths to plumb in pursuit of creating a user experience that truly resonates across different cultures. Below you’ll find more code examples and insights to advance your project’s global reach.

Handling Right-to-Left (RTL) Languages

For languages like Arabic or Hebrew, you may need to adjust UI elements to support right-to-left text. Godot 4 introduced improved support for RTL languages. While this system is complex and may require extensive UI adjustments, here’s a basic example of how to modify the text direction:

var rtl_locales = ["ar", "he"]  // Add more RTL locales as needed
func check_and_set_rtl(locale):
    var is_rtl = rtl_locales.has(locale)
    $Label.autowrap = true
    $Label.alignment = is_rtl ? Label.ALIGN_RIGHT : Label.ALIGN_LEFT

To utilize this function, you would call check_and_set_rtl with the target locale whenever you are loading or changing languages in your game.

Loading a Specific Translation File at Runtime

In some cases, you might wish to download and load translation files at runtime, particularly for games that receive regular content updates. Here’s how you might load a translation file from a remote URL:

func load_translation_from_url(url):
    var http_request = HTTPRequest.new()
    add_child(http_request)
    
    http_request.connect("request_completed", self, "_on_request_completed")
    http_request.set_download_file("res://downloads/translation.translated")
    http_request.request(url)

func _on_request_completed(result, response_code, headers, body):
    var translation = OptimizedTranslation.new()
    if translation.load("res://downloads/translation.translated"):
        ProjectSettings.get_singleton().add_translation(translation)
        emit_signal("language_changed")

Fallback Translations

To ensure that users do not encounter any missing translations, it’s prudent to provide a fallback language, often English, in case a string isn’t available in the user’s chosen language.

func get_translation(key):
    var text = tr(key)
    if text == "":
        OS.set_locale("en")  // Fallback to English
        text = tr(key)
    OS.set_locale(current_locale)  // Switch back to the current locale
    return text

Localizing Non-Text Elements

Localization doesn’t end with text. Icons, images, and other assets might also need adjustments based on cultural context. Use a similar approach to set the correct resource:

var localized_images = {
    "en": preload("res://images/welcome_en.png"),
    "es": preload("res://images/welcome_es.png")}

func set_localized_image(locale):
    var image_texture = localized_images[locale] if localized_images.has(locale) else localized_images["en"]
    $LocalizedWelcomeImage.texture = image_texture

Adjusting Font Sizes for Different Languages

Some languages require different font sizes for proper legibility. For instance, scripts with more complex characters, like Chinese or Japanese, may benefit from larger fonts.

var font_sizes = {
    "en": 14,
    "ja": 16}

func adjust_font_size_for_locale(locale):
    var size = font_sizes[locale] if font_sizes.has(locale) else font_sizes["en"]
    $Label.custom_fonts/font_size = size

By integrating these examples into your localization workflow, you will significantly improve the global appeal and accessibility of your Godot games. We are enamored by the limitless possibilities that Godot 4 provides and are diligent in our pursuit to unravel every potential it unlocks.

Our passion for exploring and sharing these discoveries is what drives us at Zenva, where we craft our tutorials to inspire and educate. Dive into the myriad possibilities that game development presents and let every line of code bridge the gaps—to connect your game with players around the world. Happy game developing!

Continuing Your Game Development Journey

The path of learning game development with Godot doesn’t have to end here. If you’ve found a spark of inspiration from our tutorials and are eager to expand upon what you’ve learned, consider taking the next step with our Godot Game Development Mini-Degree. This comprehensive learning track is designed to escalate your skills, whether you’re at the beginning of your game development journey or looking to broaden your existing capabilities. With a catalog covering the essentials of Godot 4, you can master the creation of diverse game genres and bring your game concepts to life.

Furthermore, if you’re interested in exploring our broader collection of courses to refine your skills or tackle new challenges, visit our Godot courses page. Zenva offers a variety of learning materials to help you from the basics to more sophisticated game development concepts. With Zenva, you can learn at your own pace, reinforce your knowledge with quizzes, and gain practical experience through project-based lessons. So no matter where you are on your development journey, Zenva can help you level up your skills and reach your full potential as a game creator.

Remember, the world of game development is expansive and filled with opportunities. Keep up the momentum, stay curious, and continue to build your expertise. We’re thrilled to be a part of your learning experience and can’t wait to see the amazing games you’ll create!

Conclusion

Unlocking the full scope of Godot’s capabilities is a considerable achievement, and with the insights from our tutorials and the expansive knowledge contained in our Godot Game Development Mini-Degree, you are well on your way to becoming a proficient game developer. The path to mastery is both challenging and rewarding, filled with continuous learning and creativity. Harness the power of Godot 4 to create immersive worlds and dynamic experiences that captivate players worldwide.

At Zenva, we stand by you on this remarkable journey. Our courses are more than just lessons—they’re stepping stones to actualizing your game development dreams. Remember, every expert was once a beginner, and with perseverance and passion, you too can craft the next great game. So why wait? Begin your next chapter with Zenva today and join the ranks of aspiring developers turning their visions into reality!

FREE COURSES
Python Blog Image

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