Sprites and Events

Hi there

I want to create a variable number of objects based on a sprite.

Is it possible to add event handlers to each created object so that I can use one block of event handling code to handle screen touches for the sprites?

How do you identify which sprite has been touched on the screen?

I know there’s an ID field for things like buttons so you can use one block of code, but how would you do this with a whole load of sprites?

Thanks

JB [import]uid: 58328 topic_id: 13381 reply_id: 313381[/import]

The way i did it was that each sprite stires in min x, max x, min y, max y collision details in its own structure, then in the event listener i loop through my objects and ask if event.x (event.x and event.y are the co ordinates of where you touched) is less than max x but greater than min x, same fir event.y and y values. Then if it is exit the loop and deal with the sprite at that index

So yeah, it means i use one handler for the 90 sprites i have on screen, handy in something like mine ir minesweeper which uses a grid [import]uid: 71799 topic_id: 13381 reply_id: 49190[/import]

Hey there Alick

Thanks very much for your reply - much appreciated.

I had thought about doing it the way you mentioned, but it does seem a rather crude method, when each object must be somehow identifiable to Corona.

I will use your idea though as a start point and see if anyone else can provide any other clues.

Thanks again!

JB [import]uid: 58328 topic_id: 13381 reply_id: 49192[/import]

Ok, I found another way.

You can assign any field to your sprite.

So say you have a sprite called HERO, assign it a field called anything you like - say, ID.

You set ID as usual…

Hero.ID = “MyHero”

Then in your event handler code, you do this little trick…

[code]if event.target.ID == “MyHero” then

…you’ve got the right sprite!!![/code]

The event.target passes back the object which the event occurred on, and from that you can get any properties that you set on that object. Clever!

The documentation states:

event.target

“The display image object associated with the touch event. This value will be nil if this was called by a Runtime Touch event.”

Being a noob, I did not realise that a sprite is just another display image object. And I did not appreciate that you can attach your own fields to any object, because of the freedom provided by LUA.

Using this, you can have just one function that handles an event, and assign that one function to all your sprites - making sure that each sprite has a unique ID or name or whatever. Then you just check the ID and act accordingly.

Hope this helps.

JB
[import]uid: 58328 topic_id: 13381 reply_id: 49204[/import]

Event.target looks rather nice actually. Might try and squeeze it into my new game and see how i get on with it, cheers! [import]uid: 71799 topic_id: 13381 reply_id: 49211[/import]