Before creating a virtual joystick, let’s look at multi-touch in GameMaker.
Each “touch” is detected as a “device”. You can read such devices from 0 to a maximum number using a loop.
How?
Create an object for managing multi-touches: obj_multitouch_manager. Place it in your room.
Also create an object that serves as a parent for all UI objects: obj_ui_parent.
In obj_multitouch_manager, add the Begin Step event, with the following contents:
var _max_devices = 4;
for (var i = 0; i < _max_devices; i++)
{
var _touch_x = device_mouse_x_to_gui(i);
var _touch_y = device_mouse_y_to_gui(i);
var _ui_at_pos = instance_position(_touch_x, _touch_y, obj_ui_parent);
var _held = device_mouse_check_button(i, mb_left);
if (_ui_at_pos != noone && _held)
{
_ui_at_pos.input(i, _touch_x, _touch_y);
}
}
Allowing a maximum of four touches, it loops through all devices and gets their touch coordinates.
It tries to find a UI instance at each touch’s position and checks if the touch is being held.
If a UI instance is found, and the touch is being held, it calls the input()method in the UI instance that was found.
The input() method is how we tell a UI instance that it’s being pressed. We pass in the ID and coordinates of the touch.
It then initialises joy_x and joy_y, which store the relative position of the joystick.
It creates touch_id, which is the ID of the touch that is using the joystick, and radius, which is the radius of the joystick derived from its sprite’s size.
It initialises the joystick’s input() function, which simply stores the ID of the touch in a variable.
Joystick Logic
Add the Begin Step event with the following contents: