Creating a text input field in a Defold game without using the built-in GUI system involves using the input text provided by the operating system's virtual keyboard. The tricky part in this approach is that you need to have a way to capture and display the user's input on the screen, which might involve using a sprite or drawing the text onto the screen.
Here's how you can handle text input in Defold with scripting:
-
Capture Keyboard Events:
Create a script to handle input and attach it to a game object. This script should manage the keyboard visibility and listen for text input events. The Defold engine will generate "text" actions when the user types on the virtual keyboard.
-
Display Text:
Create a dynamic text label using a label component that will display the user's input. This text will be updated every time the user types or deletes a character.
Here's an example of how this could be implemented in Lua:
local function update_text_label(self)
-- Update the text label with the current input text
label.set_text("#text_label", self.text)
end
function init(self)
self.text = ""
self.keyboard_shown = false
-- Define action names for easier access
self.ACTION_TOUCH = hash("touch")
self.ACTION_TEXT = hash("text")
self.ACTION_BACKSPACE = hash("backspace")
end
function on_input(self, action_id, action)
if action_id == self.ACTION_TOUCH and action.pressed then
-- User touched the screen, toggle the keyboard
if not self.keyboard_shown then
self.keyboard_shown = true
gui.show_keyboard(gui.KEYBOARD_TYPE_DEFAULT, false)
else
self.keyboard_shown = false
gui.hide_keyboard()
end
end
if self.keyboard_shown then
if action_id == self.ACTION_TEXT then
-- Concatenate the new character
self.text = self.text .. action.text
update_text_label(self)
elseif action_id == self.ACTION_BACKSPACE and action.repeated then
-- Remove the last character
self.text = string.sub(self.text, 1, -2)
update_text_label(self)
end
end
end
function final(self)
if self.keyboard_shown then
gui.hide_keyboard()
end
end
In this example, #text_label refers to a label component you have added to a game object. Make sure that the label component's id matches the one you're using in the label.set_text function.
Remember to include the necessary input bindings for "text" and "backspace" actions and that they are activated in your game project settings under the "input" section.
This script provides the basic functionality needed for a text input system without GUI and relies on a label component to display the text on the screen. Keep in mind that displaying text as the user types can become complex if you need to support things like cursor placement, text selection, or multi-line input. For such cases, integrating or developing a more sophisticated text rendering solution may be necessary.