Quick Links: Download Gideros Studio | Gideros Documentation | Gideros community chat | DONATE
How to setup a sprite to return id on mouse/touch event? — Gideros Forum

How to setup a sprite to return id on mouse/touch event?

arjunr24724arjunr24724 Member
edited January 2013 in Game & application design
Hi.
I've been trying to use OO in Gideros. So I created a "bubble" class from Bitmap as my sprite class, and created a local var "id" in the class.

I then used a for loop to generate an array of bubbles and stored an id to each bubble.
In the bubble class, when I called print(id) on touch/mouse event, it triggered every bubble's event function, and also returned the same id for every bubble.

Eg: (unnecessary code removed)
Bubble class:
GCbubble = gideros.class(Bitmap)
local myId = 0;

function GCbubble:onMouseDown(event)
print(myId);
end

Level Class:
function GClevel:setupLevel()
for i=1, cols*rows, 1 do
bubbleArray[i]=GCbubble.new(Texture.new("char.png"));
bubbleArray[i]:setId(i);
sceneCamera:addChild(bubbleArray[i]);
end

If the loop generates10 bubbles and I touch any 1 of them, i get "10" printed 10 times due to each bubble triggering the function.

Any way I can only make the touched bubble return its id?
Tagged:

Comments

  • ar2rsawseenar2rsawseen Maintainer
    Accepted Answer
    Firstly to trigger only specific touched bubble even, you need to use it like this:
    function GCbubble:onMouseDown(event)
        if self:hitTestPoint(event.x, event.y) then
            print(myId);
        end
    end
    But it seems that you are storing id locally for all the bubbles, if you want to have each bubble it's own id, you should store it like class property
    function GCbubble:init()
        self.id = 0
    end
     
    function GCbubble:setId(i)
        self.id = i
    end
     
    function GCbubble:onMouseDown(event)
        if self:hitTestPoint(event.x, event.y) then
            print(self.id)
        end
    end

    Likes: arjunr24724

    +1 -1 (+1 / -0 )Share on Facebook
  • Thanks.

    Just stumbled onto the soln myself (after scratching my head for the past couple of hrs), and your soln is exactly what I ended up doing =D>

    Likes: ar2rsawseen

    +1 -1 (+1 / -0 )Share on Facebook
  • you might also want to use the
    event:stopPropogation()
    after the
    print(self.id)
    while it might not make much of a difference but it can save you a bit when you have a couple of handlers and the events trigger each of the handlers.

    Likes: arjunr24724

    twitter: @ozapps | http://www.oz-apps.com | http://howto.oz-apps.com | http://reviewme.oz-apps.com
    Author of Learn Lua for iOS Game Development from Apress ( http://www.apress.com/9781430246626 )
    Cool Vizify Profile at https://www.vizify.com/oz-apps
    +1 -1 (+1 / -0 )Share on Facebook
  • thanks. good to know and i think important to implement right from the start.
Sign In or Register to comment.