Thursday, August 2, 2012

Android Game Development and Corona SDK Notes Part 2 - basic screen interactions


We are going to explore interacting with the environment more via image objects and event listeners.

From the previous posting, we looked at how to display things on screen and click on them. Now we are going to go a few steps further.

How do we add something to the background so it blends in? You can create images with a transparent background. This can be easily accomplished using gimp. See the following tutorial for some tips:
http://cafesuccess.blogspot.com/2006/09/making-images-with-transparent.html

Suppose we want to have multiple objects that we can touch. Can we use one event listener for all of them? How would we distinguish between them?

Based on the api documentation here : http://developer.coronalabs.com/content/events-and-listeners

You can use event.target to easily distinguish objects.

Here is an example:

local selectObj = function( event )
 local t = event.target
 local phase = event.phase


 if "began" == phase then
  
  if t.id == "hand" then
    print "selected hand"
  elseif t.id == "eye" then
      print "selected eye"
  
  end
  
 end

end

local bg = display.newImage("screen1.png")
local hand = display.newImage("hand2.png")
local eye = display.newImage("eye.png")

hand.x = 5
hand.y = 50
hand.id = "hand"

hand:addEventListener("touch",selectObj)

eye.x = 5
eye.y = 80
eye.id = "eye"
eye:addEventListener("touch",selectObj)


When you click the eye object it says "selected eye." When you click the hand object it says "selected hand."

Can we indicate on the screen somehow what object is selected.

We can use this code to underline the image:

   local selectedRect = display.newRect(t.x- t.contentWidth/2,t.y+ t.contentHeight/2,t.contentWidth,5)

This can be placed in the if block like so:

 if t.id == "hand"  then
    --print "selected hand"
   local selectedRect = display.newRect(t.x- t.contentWidth/2,t.y+ t.contentHeight/2,t.contentWidth,5)
   
  elseif t.id == "eye" then
      --print "selected eye"
   local selectedRect = display.newRect(t.x- t.contentWidth/2,t.y+ t.contentHeight/2,t.contentWidth,5)
  
  end

But the mark stays if you select the other object. Can we have so it only selects one?

First define selectedRect var outside the listener. We will remove the display object selectedRect before displaying again.

    if selectedRect ~= nil then
     selectedRect:removeSelf()
    end

Do this before displaying the object.
    selectedRect = display.newRect(t.x- t.contentWidth/2,t.y+ t.contentHeight/2,t.contentWidth,5)

More to come...

1 comment:

  1. Corona SDK is the quickest & simplest way to generate successful commercially cross platform mobile games. You don’t need to be a programming professional to generate games using Corona. Corona SDK is the number device for generating fun, simple blockbuster games.

    ReplyDelete