You can do this from both script components and gui script components. First you need to acquire input so that the script gets calls to it’s on_input function:
function init(self)
msg.pos(".", "acquire_input_focus")
end
Once you have acquired input focus you will start seeing calls to your on_input() function:
function on_input(self, action_id, action)
print("I was called with action_id", action_id)
pprint(action)
end
Any action you define in your input bindings will be passed along as the action_id
to the input function when it’s triggered. Touch and mouse button one will be sent with action_id “touch”.
function on_input(self, action_id, action)
if action_id == hash("touch") and action.pressed then
print("You touched", action.x, action.y)
-- action.screen_x and action.screen_y are translated screen coordinates
end
end
You can read the screen dimensions in two ways:
- Get the value from game.project using
sys.get_config("display.width")
and sys.get_config("display.height")
. This will not get updated values if the screen was resized.
- Use a custom render script and read
render.get_window_width()
and render.get_window_height()
? to the get the current window dimensions. Do a msg.post() of these values or store them in a shared module for easy access from your script files.
So, to wrap this up I think it’s enough to use the first of the two ways to get screen size and compare that value with the x and y coordinate where the user touched/clicked:
function on_input(self, action_id, action)
if action_id == hash("touch") and action.pressed then
if action.x > tonumber(sys.get_config("display.width")) / 2 then
-- right
else
-- left
end
end
end
Read more about how input is handled in Defold here.