Corona – Events

Think of notifications from the program about things that have happened in the program. Use events to determine when an object is tapped or when period of time has passed. Use events to animate things and react to user interaction.

Listeners and Handlers

Listeners are objects that have been assigned to respond to an event. Handlers are the functions that are run when an event occurs. Think of listeners as waiting for and notifying their handlers when the event occurs.

Most objects in Corona can be assigned a listener. Use the addEventListener() method to assign the listener. For example imagine you want a create an event is fired when you tap an image. You might write the following. Try it for yourself.

  1. Create a new folder to work in
  2. Open a new text file and save it to your folder with the name main.lua
  3. Copy an image to use in the example to your folder

Add the following code to main.lua:

-- Create an image and position it in the center of the screen
local invader = display.newImage("invader_04.png")

invader.x = display.contentWidth / 2
invader.y = display.contentHeight / 2

-- Define a handler
local function tapInvader( event ), {time=1000, rotation=invader.rotation+360})

-- Add an event listener to the invader
invader:addEventListener("tap", tapInvader)

I added a few comments to the code to explain what is going on. Any line that begins with “–” is ignored and the rest of the line can be used to write a message or description of your code.

Test your project and tap the invader. With each tap it rotates 360!


Leave a Reply

Your email address will not be published. Required fields are marked *