Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· openaiHugging Face Suzhen/CodeChat

Lua script example for Defold engine with window_resized message

  1. User

    Lua script example for Defold engine with window_resized message

  2. Assistant

    In the Defold game engine, you can listen for window_resized messages using a Lua script attached to a game object. To handle window resizing, you define a on_message function within your script, which automatically gets invoked whenever a message is sent to the script's game object.

    Here's a simple example of a Lua script that handles the window_resized message in Defold:

    -- name this script 'resize_handler.script'
    
    function init(self)
        -- Register this game object to receive `window_resized` messages.
        -- These messages are sent by the engine when the application window is resized.
        msg.post(".", "acquire_input_focus")  -- This also handles certain input messages.
    end
    
    -- `on_message` is called when this game object receives a message.
    function on_message(self, message_id, message, sender)
        if message_id == hash("window_resized") then
            -- Perform any actions needed when the window is resized
            -- `message.width` and `message.height` contain the new width and height of the window
            print("The window was resized to: " .. message.width .. "x" .. message.height)
            
            -- Here you could also adjust your GUI scenes, camera projection matrices,
            -- or anything else that depends on the window size.
            
            -- For example, to adjust a GUI:
            --[[
            local new_width = message.width
            local new_height = message.height
            local gui_nodes = gui.get_nodes()
            for i, node in ipairs(gui_nodes) do
                local adjust_x = new_width / initial_width -- Assuming you've stored initial_width somewhere
                local adjust_y = new_height / initial_height -- Assuming you've stored initial_height somewhere
                gui.set_position(node, vmath.vector3(gui.get_position(node).x * adjust_x, gui.get_position(node).y * adjust_y, 0))
            end
            ]]
        end
    end
    
    

    Ensure that this script is attached to a game object in your Defold project and the game object is loaded into your collection at runtime for the script to receive the window_resized message effectively.

    Remember to tailor the sample code to fit your application's needs. You will want to implement specific behavior on a window resize event, like adjusting your view or re-scaling GUI elements, which requires knowing the original and target dimensions to calculate scaling factors.