Article Tutorials/Touch Input and Mouse Input

From GiderosMobile
Revision as of 23:53, 29 November 2019 by Plicatibu (talk | contribs) (Created page with "== Touch Input and Mouse Input == === Touch Input === You will no doubt want people to tap a Start Button to get the game going from your title screen. Here’s how to set up...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Touch Input and Mouse Input

Touch Input

You will no doubt want people to tap a Start Button to get the game going from your title screen. Here’s how to set up a button. This example will print the co-ordinates where the player taps the button.

local yinyang = Sprite.new()
local yinyangimg = Bitmap.new(Texture.new("images/yinyang.png"))
yinyang:addChild(yinyangimg)

local function imagetouch(button, event)
    if button:hitTestPoint(event.touch.x, event.touch.y) then
        local x = event.touch.x
        local y = event.touch.y
        print("touched: X=" .. x .. " Y=" .. y)
    end
end

yinyang:setPosition(100,200)
yinyang:addEventListener(Event.TOUCHES_END, imagetouch, yinyang)

stage:addChild(yinyang)


When you run this code, you will see the usual image on the screen. Click on it with your mouse in the Player. You will see the co-ordinates of where you clicked on the image displayed in the console Output area of Gideros Studio.
The other events are: TOUCHES_BEGIN, TOUCHES_MOVE and TOUCHES_CANCEL.

Mouse Input

Handling Mouse Input is pretty much the same as Touch Input, however you don’t use the ‘touch’ handler nor event information. The code for Mouse Input is below.

local yinyang = Sprite.new()
local yinyangimg = Bitmap.new(Texture.new("images/yinyang.png"))
yinyang:addChild(yinyangimg)
local function imagetouch(button, event)
    if button:hitTestPoint(event.x, event.y) then
        local x = event.x
        local y = event.y
        print("clicked: X=" .. x .. " Y=" .. y)
    end
end

yinyang:setPosition(100,200)
yinyang:addEventListener(Event.MOUSE_UP, imagetouch, yinyang)

stage:addChild(yinyang)


You should check for when the mouse button is UP on your object as the player may change their mind and move the mouse away so as to not activate the button. This is more common on iOS and you will want to use Event.TOUCHES_END if programming with touches for mobile devices.

The other Mouse options are: MOUSE_DOWN and MOUSE_MOVE.

You can download the yinyang image from here: File:Yinyang.png


Note: This tutorial was written by Jason Oakley and was originally available Here: http://bluebilby.com/2013/04/26/gideros-mobile-tutorial-touch-input-and-mouse-input/.