Virtual Pad Example for Defold
This project demonstrates how to use universal virtual pad in Defold games. The main folder hosts a minimal scene: the player listens to move messages, while controls.gui_script captures input and forwards it to gui/virtual_pad.lua.
Hooking It Up
local VirtualPad = require "gui.virtual_pad"
function init(self)
msg.post(".", "acquire_input_focus")
self.pad = VirtualPad.new("virtual_pad")
self.pad.fixed_position = false
self.pad.always_visible = false
end
function on_input(self, action_id, action)
if action_id == hash("touch") then
self.touch = action
elseif action_id == hash("touch_multi") then
self.touch_multi = action
end
end
function update(self, dt)
self.pad:on_input(self.touch, self.touch_multi)
self.pad:update(dt)
local x, y = self.pad:get_data()
msg.post("player", "move", { released = (x == 0 and y == 0), x = x, y = y })
end
Virtual Pad Features (gui/virtual_pad.lua)
- Dynamic or fixed placement:
fixed_positionlets you anchor the pad or spawn it under the finger on first touch. - Flexible visibility: make the pad always visible, show it only before the first touch (
always_visible_before_first_input), or hide it immediately on release. - Two activation zones:
set_bordersandset_borders_2constrain the screen regions that accept touches—ideal when you need to keep one half of the screen for buttons. - Full multitouch support: the module consumes both
touchandtouch_multi, remembers the active finger, and can ignore individual ids viaset_blocked_touch. - Normalized output and a safe zone:
get_data()returns values in the [-1; 1] range, whileis_safe()/is_in_safe_area()tell you when the stick snaps back to the center. - Screen adaptation:
on_resize()recalculates GUI node positions so the pad stays correct across orientations and aspect ratios. - State control:
set_enabled()/is_enabled(), automaticreset(), and thesafe_zone_timetimer make it easy to fade the pad out during cutscenes or tutorials.
Project Layout
gui/virtual_pad.guiandgui/virtual_pad.lua— the visual part and the logic of the stick.main/controls.gui+main/controls.gui_script— a sample UI screen that shows how the pad is initialized.main/player.script— a simple game object that reacts tomovemessages and moves around.
Use this sample as a starting point and tune the visuals or sensitivity for your game